gpt4 book ai didi

python - 在 Flask-APScheduler 作业中查询模型引发应用程序上下文 RuntimeError

转载 作者:太空狗 更新时间:2023-10-29 18:08:07 27 4
gpt4 key购买 nike

我想使用 Flask-APScheduler 运行一个查询 Flask-SQLAlchemy 模型的作业。当作业运行时,我得到 RuntimeError: application not registered on db instance and no application bound to current context。如何运行查询数据库的作业。

from flask_apscheduler import APScheduler

scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()
from models import User

def my_job():
user = User.query.first()
print(user)

错误发生在查询过程中,在打印之前。该数据库在应用程序的其余部分中用于其他查询。

我尝试在设置扩展程序时添加 with app.app_context(): 但没有成功。

with app.app_context()
scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()

完整的追溯是:

ERROR:apscheduler.executors.default:Job "run_in (trigger: interval[0:00:10], next run at: 2016-10-18 23:00:53 CEST)" raised an exception
Traceback (most recent call last):
File "/Users/user/.virtualenvs/myfolder/lib/python2.7/site-packages/apscheduler/executors/base.py", line 125, in run_job
retval = job.func(*job.args, **job.kwargs)
File "/Users/user/Documents/myfolder/myfolder/myfile.py", line 19, in myjob
user = User.query.all()
File "/Users/user/.virtualenvs/myfolder/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 454, in __get__
return type.query_class(mapper, session=self.sa.session())
File "/Users/user/.virtualenvs/myfolder/lib/python2.7/site-packages/sqlalchemy/orm/scoping.py", line 71, in __call__
return self.registry()
File "/Users/user/.virtualenvs/myfolder/lib/python2.7/site-packages/sqlalchemy/util/_collections.py", line 878, in __call__
return self.registry.setdefault(key, self.createfunc())
File "/Users/user/.virtualenvs/myfolder/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 704, in create_session
return SignallingSession(self, **options)
File "/Users/user/.virtualenvs/myfolder/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 149, in __init__
self.app = db.get_app()
File "/Users/user/.virtualenvs/myfolder/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 845, in get_app
raise RuntimeError('application not registered on db '
RuntimeError: application not registered on db instance and no application bound to current context

最佳答案

Flask-SQLAlchemy 需要一个活跃的应用上下文来执行查询。虽然 Flask-APScheduler 确实将 APScheduler 与 Flask 集成,但它不会在运行每个作业时推送应用程序上下文。

您需要在作业中推送应用上下文。设置扩展程序时推送应用程序上下文不会执行任何操作。

def my_job():
with app.app_context():
...

您可能需要所有作业的应用上下文。您可以子类化扩展并覆盖 run_job

from flask_apscheduler import APScheduler as _BaseAPScheduler

class APScheduler(_BaseAPScheduler):
def run_job(self, id, jobstore=None):
with self.app.app_context():
super().run_job(id=id, jobstore=jobstore)
# super(APScheduler, self) in Python 2

关于python - 在 Flask-APScheduler 作业中查询模型引发应用程序上下文 RuntimeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40117324/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com