Flask 如何使用芹菜任务访问orm?
我正在尝试使用sqlalchemy+Cellery beats为数据库中特定类型的对象翻转布尔标志。但是如何从tasks.py文件访问ormFlask 如何使用芹菜任务访问orm?,flask,celery,flask-sqlalchemy,celery-task,celerybeat,Flask,Celery,Flask Sqlalchemy,Celery Task,Celerybeat,我正在尝试使用sqlalchemy+Cellery beats为数据库中特定类型的对象翻转布尔标志。但是如何从tasks.py文件访问orm from models import Book from celery.decorators import periodic_task from application import create_celery_app celery = create_celery_app() # Create celery: http://flask.pocoo.org
from models import Book
from celery.decorators import periodic_task
from application import create_celery_app
celery = create_celery_app()
# Create celery: http://flask.pocoo.org/docs/0.10/patterns/celery/
# This task works fine
@celery.task
def celery_send_email(to,subject,template):
with current_app.app_context():
msg = Message(
subject,
recipients=[to],
html=template,
sender=current_app.config['MAIL_DEFAULT_SENDER']
)
return mail.send(msg)
#This fails
@periodic_task(name='release_flag',run_every=timedelta(seconds=10))
def release_flag():
with current_app.app_context(): <<< #Fails on this line
books = Book.query.all() <<<< #Fails here too
for book in books:
book.read = True
book.save()
返回到当前的app.app\u context()行
如果删除当前的\u app.app\u context()行,将出现以下错误:
RuntimeError: application not registered on db instance and no application bound to current context
对于芹菜任务,是否有特定的方式访问Alchemy orm?还是有更好的方法来实现我的目标
到目前为止,唯一有效的解决方法是在my application factory模式中的db.init_app(app)
之后添加以下行:
db.app=app
我按照此回购创建了我的芹菜应用程序您会遇到此错误,因为当前的应用程序需要应用程序上下文才能工作,但您正在尝试使用它设置应用程序上下文。您需要使用实际的应用程序来设置上下文,然后您可以使用
current\u app
with app.app_context():
# do stuff that requires the app context
或者,您可以使用类似于to subclassCellery.Task
中所述的模式,以便默认情况下它了解应用程序上下文
from celery import Celery
def make_celery(app):
celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
return celery
celery = make_celery(app)
from celery import Celery
def make_celery(app):
celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
return celery
celery = make_celery(app)