How to access the orm with celery tasks?
You're getting that error because current_app
requires an app context to work, but you're trying to use it to set up an app context. You need to use the actual app to set up the context, then you can use current_app
.
with app.app_context(): # do stuff that requires the app context
Or you can use a pattern such as the one described in the Flask docs to subclass celery.Task
so it knows about the app context by default.
from celery import Celerydef 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)