首页 > 解决方案 > 在视图函数之外访问 Flask-SQLAlchemy 数据库

问题描述

我创建了一个小型 Flask 应用程序,它将其数据存储在我通过 flask-sqlalchemy 访问的 sqlite 数据库中。

但是,当我运行它时,我收到以下错误:

RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

我已经调试了我的应用程序,现在知道这个错误源于这两个函数:

def user_exists(email):
    if User.query.filter_by(email = email).count() == 0:
        return False
    else:
        return True

def get_user(email):
    user = User.query.filter_by(email = email).first()
    return user

现在我想知道:是否不可能通过视图函数之外的 flask-sqlalchemy 访问数据库?

为了进一步了解,我添加了配置烧瓶应用程序的文件:

presentio.py

from app import create_app

app = create_app(os.getenv("FLASK_CONFIG", "default"))

应用程序/初始化.py

from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from config import config

mail = Mail()
db = SQLAlchemy()


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    mail.init_app(app)
    db.init_app(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix = "/auth")

    from .text import text as text_blueprint
    app.register_blueprint(text_blueprint, url_prefix = "/text")

    return app

标签: pythondatabaseflashsqlalchemyflask-sqlalchemy

解决方案


创建烧瓶应用程序后,您需要为其提供上下文。这是在视图函数中自动完成的,但在这些函数之外,您需要在创建应用程序后执行此操作:

app.app_context().push()

请参阅文档:https ://flask-sqlalchemy.palletsprojects.com/en/2.x/contexts/


推荐阅读