已经挺久没做flask开发了,现在主要为了给大家分享一些关于之前flask项目开发的经验总结,希望对大家有所帮助!
flask启动项目里的初始化文件一般包括,初始化app,初始化配置config,注册蓝图等步骤!
最中规中矩的方式就是每次新增一个新的模块就在初始化文件中手动加两行代码用于蓝图的注册!
项目配置文件config.py:
其中SECRET_KEY一定要设置,且最好为随机数,可以防止csrf,不然会出现 Must provide secret_key to use csrf 错误提醒!
# -*- coding: utf-8 -*-
import os
class Config(object):
SECRET_KEY = 'wwzgYXYPI/ytEfA4wP1W5KucP21vaDaiusGaO5OlaOBw5O1Bg1f3nmg+G0VkauQPQEodiI4AKXF05rLPNmvquFYC'
@staticmethod
def init_app(app):
# staticmethod可以在类不需要实例化时调用方法
pass
class DevConfig(Config):
DEBUG = True
SQLALCHEMY_ECHO = True
CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_BACKEND_URL = 'redis://localhost:6379/0'
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:123456@ip:port/dev_db"
config = {'development': DevConfig}
生成随机字符串用于SECRET_KEY:
import os, base64
def create_key(length):
random_str = os.urandom(length)
byte_ret = base64.b64encode(random_str) # 生成byte类型字符串: b'Easpoammc+/'
result = byte_ret.decode('unicode_escape')
return result
if __name__ == '__main__':
create_key(66)
# 测试结果:wwzgYXYPI/ytEfA4wP1W5KucP21vaDaiusGaO5OlaOBw5O1Bg1f3nmg+G0VkauQPQEodiI4AKXF05rLPNmvquFYC
初始化__init__.py文件如下:
from flask import Flask, redirect, url_for
from config import config
from flask_sqlalchemy import SQLAlchemy
from .extensions import celery
from flask_login import LoginManager, login_required, current_user
# 实例化数据库对象
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
def create_app(config_name='development'):
'''
1: 创建一个app应用程序
2: 把配置对象传递给所创建的app
'''
app = Flask(__name__)
app.config.from_object(config[config_name])
# 将app中的配置文件应用到db中
db.init_app(app)
celery.init_app(app)
login_manager.init_app(app)
login_manager.login_message = '请先登录'
from app.auth import auth as auth_bp
app.register_blueprint(auth_bp, url_prefix='/auth')
from app.main import main as main_bp
app.register_blueprint(main_bp, url_prefix='/main')
# 登录后默认跳转页
@app.route('/')
@login_required
def index():
return redirect(url_for('main.index'))
return app
很显然如果开发的功能较少的情况下,以上那种针对蓝图逐个注册是问题不大,一旦项目业务越来越复杂时,以上这种方式会出现一大片注册代码,且都是做同样的事,既不美观也不简洁,所以可以采用批量注册的方式进行代码优化,封装动态注册蓝图函数!
- 方式一
import importlib
import os
def auto_register_blueprint(app):
path = os.path.dirname(os.path.abspath(__file__))
base_file = path.split('\\')[-1]
for filename in os.listdir(path):
file_path = os.path.join(path, filename)
if not os.path.isdir(file_path):
continue
if not os.path.exists(os.path.join(file_path, '__init__.py')):
continue
auto_blueprint = importlib.import_module(f'{base_file}.' + filename).__dict__[filename]
app.register_blueprint(auto_blueprint, url_prefix=f'/{filename}')
- 方式二
from werkzeug.utils import import_string
import os
def auto_register_blueprint(app):
path = os.path.dirname(os.path.abspath(__file__))
base_file = path.split('\\')[-1]
for filename in os.listdir(path):
file_path = os.path.join(path, filename)
if not os.path.isdir(file_path):
continue
if not os.path.exists(os.path.join(file_path, '__init__.py')):
continue
auto_blueprint = import_string(f'{base_file}.' + filename + ".__init__:" + filename)
app.register_blueprint(auto_blueprint, url_prefix=f'/{filename}')
优化后的初始化__init__.py文件如下:
def create_app(config_name='development'):
'''
1: 创建一个app应用程序
2: 把配置对象传递给所创建的app
'''
app = Flask(__name__)
app.config.from_object(config[config_name])
# 将app中的配置文件应用到db中
db.init_app(app)
celery.init_app(app)
login_manager.init_app(app)
login_manager.login_message = '请先登录'
auto_register_blueprint(app)
# 登录后默认跳转页
@app.route('/')
@login_required
def index():
return redirect(url_for('main.index'))
return app
项目启动管理文件manage.py
# -*- coding: utf-8 -*-
from flask_script import Manager, Shell, Server
from app import create_app, db
app = create_app('development')
manager = Manager(app)
def make_shell_context():
return dict(app=app, db=db)
manager.add_command('shell', Shell(make_context=make_shell_context))
if __name__ == '__main__':
manager.run()
以上的这些项目基本文件都配置好,项目就可以启动了,进入shell命令:
python manage.py shell
项目启动命令,其中的host、port为可选参数:
python manage.py runserver --host 0.0.0.0 --port 8888
单个子模块的蓝图配置,例如针对account模块蓝图注册,在account文件下新建__init__.py文件,如下:
from flask import Blueprint
account = Blueprint('account', __name__)
from .forms import *
from .views import *
from .models import *