flask-sqlalchemy 工程化的问题?
官方文档里的例子是直接在 app.py
里初始化数据库的,然后去用 db
但实际项目肯定不会这么做,要放文件夹里然后引入的,但我引入后就报错了
nexpect System Error - The setup method 'shell_context_processor' can no longer be called on the application. It has already handled its first request, any changes will not be applied consistently.\nMake sure all imports, decorators, functions, etc. needed to set up the application are done before running it.
a.py
from flask import current_appfrom flask_sqlalchemy import SQLAlchemy
DB = SQLAlchemy()
setting = current_app.config["Database"]
current_app.config["SQLALCHEMY_DATABASE_URI"] = f'mysql+pymysql://{setting["DB_USER"]}:{setting["DB_PASS"]}@{setting["DB_HOST"]}/{setting["DB_NAME"]}'
DB.init_app(current_app)
b.py
from model.user import Userfrom a import DB
class Account:
@staticmethod
def login(username, password):
user = DB.session.execute(DB.select(User).filter_by(name=username)).scalar_one()
return "token"
回答:
current_app
current_request
这些current对象只存在地 FlaskApp的上下文当中, 平时是不存在的. 要用的话, 需要with app.test_context()
(可能是这个名字).
在文件中直接使用, 必须使用自己的app对象, 不能用current_app
以上是 flask-sqlalchemy 工程化的问题? 的全部内容, 来源链接: utcz.com/p/938940.html