flask使用工厂函数注册一些配置参数进去的时候竟然报错了,我的model模块无论怎么样都无法import db变量,后来把
db = SQLAlchemy(app) #改为 db = SQLAlchemy()
报了一个错误
AssertionError: The sqlalchemy extension was not registered to the current application. Please make sure to call init_app() first.
翻阅资料,如果是不能使用sqlalchemy方法初始化配置,那么我们可以在工厂函数种使用
db.init_app(app)
这种方式来初始化数据库的配置
我的工厂函数整个如下
#!/usr/bin/python3 #coding:utf-8 from flask import Flask from .web import web from config import load_json from .common import db config = load_json() def create_app(): app = Flask(__name__) secret_key(app) configure_database(app) db.init_app(app) register_blueprint(app) configure_mail(app) mail.init_app(app) return app def secret_key(app): app.secret_key = 'merci' def configure_database(app): #查询时会显示原始SQL语句 #app.config['SQLALCHEMY_ECHO'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://{db_user}:{db_pass}@{db_host}:{db_port}/{db_name}?charset=utf8mb4'.format( db_user=config['db']['db_user'], db_pass=config['db']['db_pass'], db_host=config['db']['db_host'], db_port=config['db']['db_port'], db_name=config['db']['db_name']) def configure_mail(app): app.config['MAIL_SERVER'] = config['mail']['mail_host'] app.config["MAIL_PORT"] = config['mail']['mail_port'] app.config["MAIL_USE_SSL"] = True app.config["MAIL_USERNAME"] = config['mail']['mail_user'] app.config["MAIL_PASSWORD"] = config['mail']['mail_pass'] def register_blueprint(app): app.register_blueprint(web, url_prefix='/')
工厂函数给我们的一些操作进行了简化,当程序初始化的时候就能把一些方法都进行初始化,所以我们可以在这个函数种做许多事
common.py公共库里面的代码如下
#!/usr/bin/python3 #coding:utf-8 from flask_sqlalchemy import SQLAlchemy from flask_mail import Mail mail = Mail() db = SQLAlchemy()