Sentry Answers>Flask>

RuntimeError: Working Outside of Application Context

RuntimeError: Working Outside of Application Context

Armin Ronacher

The Problem

Click to Copy
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:

Click to Copy
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:

  • SentryFlask Error Monitoring
  • Syntax.fmListen to the Syntax Podcast
  • Community SeriesIdentify, Trace, and Fix Endpoint Regression Issues
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark of Functional Software, Inc.