raphaelrk
raphaelrk

Reputation: 827

Celery outside of flask application context

Getting the following error running a celery task, even with a Flask application context:

raised unexpected: RuntimeError('Working outside of application context.\n\nThis typically means that you attempted to use functionality that needed\nto interface with the current application object in some way. To solve\nthis, set up an application context with app.app_context().  See the\ndocumentation for more information.',)

Traceback (most recent call last):
  File "/usr/lib/python3.6/site-packages/celery/app/trace.py", line 382, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/usr/lib/python3.6/site-packages/celery/app/trace.py", line 641, in __protected_call__
    return self.run(*args, **kwargs)
  File "/app/example.py", line 172, in start_push_task
    }, data=data)
  File "/app/push.py", line 65, in push
    if user and not g.get('in_celery_task') and 'got_user' not in g:
  File "/usr/lib/python3.6/site-packages/werkzeug/local.py", line 347, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/usr/lib/python3.6/site-packages/werkzeug/local.py", line 306, in _get_current_object
    return self.__local()
  File "/usr/lib/python3.6/site-packages/flask/globals.py", line 44, in _lookup_app_object
    raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context().  See the
documentation for more information.

Any way to fix this?

Upvotes: 0

Views: 2405

Answers (1)

raphaelrk
raphaelrk

Reputation: 827

For me, the issue was that I had import celery instead of from app import celery.

Here's some more of my setup code for anyone who stumbles across here in the future:

app.py

def make_celery(app):
    app.config['broker_url'] = 'amqp://rabbitmq:rabbitmq@rabbit:5672/'
    app.config['result_backend'] = 'rpc://rabbitmq:rabbitmq@rabbit:5672/'

    celery = Celery(app.import_name, backend=app.config['result_backend'], broker=app.config['broker_url'])
    celery.conf.update(app.config)

    class ContextTask(Task):
        abstract = True

        def __call__(self, *args, **kwargs):
            with app.test_request_context():
                g.in_celery_task = True
                res = self.run(*args, **kwargs)
                return res

    celery.Task = ContextTask
    celery.config_from_object(__name__)
    celery.conf.timezone = 'UTC'
    return celery

celery = make_celery(app)

In the other file:

from app import celery

Upvotes: 1

Related Questions