flask-sqlalchemy 工程化的问题?

作者站长头像
站长
· 阅读数 19

官方文档里的例子是直接在 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"
回复
1个回答
avatar
test
2024-07-01

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

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

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容