在Flask-APScheduler作业中查询模型会引发应用程序上下文运行错误

问题描述

我希望使用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

解决方案

我通过将应用程序添加到应用程序工厂中的SQLAlChemy实例修复了此问题:

def create_app():
    new_app = Flask(__name__)
    new_app.config.from_object('config')
    new_app.secret_key = os.urandom(12)
    db.init_app(new_app)
    db.app = new_app
    return new_app

我确实尝试过使用应用上下文,但从未成功。

相关文章