Python, Celery, Flask, “working outside of application context”

我怕爱的太早我们不能终老 提交于 2020-01-30 13:04:12

问题


I am trying to schedule tasks using Celery and Python for a Flask app. I basically want to run a function in another directory every x amount of time and make it a celery task. I import the function test_check and I try and put it under a celery task called testcheck(), however, I get the error:

working outside of application context

How can I fix this? Here is my setup:

from app import app
from celery import Celery
from datetime import timedelta
from app.mod_check.views import test_check

celery = Celery(__name__,
             broker='amqp://guest:@localhost/',
             backend='amqp://guest:@localhost/'
             )

celery.config_from_object(__name__)

@celery.task
def add(x, y):
    print "celery working!"
    return x + y

@celery.task
def testcheck():
        test_check()

CELERYBEAT_SCHEDULE = {
    'add-every-30-seconds': {
        'task': 'tasks2.testcheck',
        'schedule': timedelta(seconds=5),
        #'args': (16, 16)
    },
}

CELERY_TIMEZONE = 'Europe/London'

回答1:


Whatever test_check is, it does something that needs a request context. Since Celery tasks are not part of the HTTP request/response cycle, you need to set up a request context manually.

with app.test_request_context():
    test_check()


来源:https://stackoverflow.com/questions/31571654/python-celery-flask-working-outside-of-application-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!