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_app
from 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 User
from 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"
阅读 2.5k
1 个回答

current_app current_request 这些current对象只存在地 FlaskApp的上下文当中, 平时是不存在的. 要用的话, 需要with app.test_context() (可能是这个名字).

在文件中直接使用, 必须使用自己的app对象, 不能用current_app

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏