
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 flaskfrom flask_sqlalchemy import sqlalchemyapp = 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 Userfrom a import DB, appclass 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”错误?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1353402.html
微信扫一扫
支付宝扫一扫