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

时间:2016-10-18 20:17:04

标签: python flask flask-sqlalchemy 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

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

我通过在app工厂中将应用程序添加到我的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

我确实尝试使用应用程序上下文,但从未奏效。