flask-sqlalchemy 工程化遇到的问题
官方文档中使用 app.py 直接初始化数据库的示例虽然简单,但在实际项目中并不可行。将数据库初始化代码封装到单独的文件中并引入时,可能会出现错误:
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. make sure all imports, decorators, functions, etc. needed to set up the application are done before running it.
该错误提示表明 flask 应用程序已经处理了第一个请求,无法再进行配置更改。这通常发生在引入数据库代码后,因为 current_app 和 current_request 等 current 对象仅存在于 flask 应用程序的上下文中。
解决方案
要解决此问题,需要在文件中使用自己的应用程序对象,而不是 current_app:
a.py
from flask import flask from flask_sqlalchemy import sqlalchemy app = flask(__name__) db = sqlalchemy() setting = app.config["database"] app.config["sqlalchemy_database_uri"] = f'mysql+pymysql://{setting["db_user"]}:{setting["db_pass"]@{setting["db_host"]}/{setting["db_name"]}' db.init_app(app)
b.py
from model.user import User from a import DB, app class Account: @staticmethod def login(username, password): with app.test_context(): user = DB.session.execute(DB.select(User).filter_by(name=username)).scalar_one() return "token"
通过将 app 作为上下文本管理器,我们可以模拟真实应用程序的上下文,从而正确初始化数据库并使用 current 对象。
以上就是Flask-SQLAlchemy 工程化时,如何避免"The setup method 'shell_context_processor' can no longer be called on the application"错误?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号