python - 在视图函数之外访问 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
解决方案
创建烧瓶应用程序后,您需要为其提供上下文。这是在视图函数中自动完成的,但在这些函数之外,您需要在创建应用程序后执行此操作:
app.app_context().push()
请参阅文档:https ://flask-sqlalchemy.palletsprojects.com/en/2.x/contexts/
推荐阅读
- python - Python dicts 如何保持密钥顺序
- angular - 使 Angular 忽略模板中的错误
- android - Jetpack Compose 第一个参数修饰符不起作用
- python - 用于从 Python 的父目录中的另一个文件调用函数?
- python-textfsm - 使用 textfsm 解析分层文本输出
- select - 如何使 Select 在 Web 组件的阴影根中正确呈现?
- c# - 保存后的 UnitOfWork 记录数据
- animation - 如何在处理时顺时针旋转一个圆圈?
- android-12 - 无法解析“SplashScreen”中的方法“installSplashScreen”
- python - 用于绘制多通道 wav 文件的 matplotlib 和大胆的变化