问题
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