Hello! 欢迎来到小浪资源网!


Flask-SQLAlchemy 工程化时,如何避免"The setup method ‘shell_context_processor’ can no longer be called on the application"错误?


Flask-SQLAlchemy 工程化时,如何避免"The setup method ‘shell_context_processor’ can no longer be called on the application"错误?

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 对象。

相关阅读