RuntimeError: Working Outside of Application Context

Armin Ronacher

The Problem

Traceback (most recent call last):
  File "app.py", line 30, in init_db
    db = get_db()
  File "app.py", line 41, in get_db
    g.sqlite_db = connect_db()
  File "/usr/local/lib/python2.7/site-packages/werkzeug/local.py", line 355, in <lambda>
    __setattr__ = lambda x, n, v: setattr(x._get_current_object(), n, v)
  File "/usr/local/lib/python2.7/site-packages/werkzeug/local.py", line 297, in _get_current_object
    return self.__local()
  File "/usr/local/lib/python2.7/site-packages/flask/globals.py", line 27, in _lookup_app_object
    raise RuntimeError('working outside of application context')
RuntimeError: working outside of application context

The Solution

Flask requires application context be available when accessing certain items, such as the g construct. Many of these accessors are simply a proxy for the current version, which is bound to the Flask application context.

For example, if you’ve got a command line app, you simply need to instantiate your app and push a context:

from flask import Flask, current_app

app = Flask(__name__)

with app.app_context():
    # within this block, current_app points to app.
    print current_app.name

Further Reading

If you’re looking to get a deeper understanding of how Flask application monitoring works, take a look at the following articles:

Join the discussionCome work with us
Share on Twitter
Bookmark this page
Ask a questionImprove this Answer

Related Answers

A better experience for your users. An easier life for your developers.

Try Sentry For FreeRequest a Demo
    TwitterGitHubDribbbleLinkedin
© 2023 • Sentry is a registered Trademark
of Functional Software, Inc.