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

The Experts

Armin Ronacher

Working Code, Happy Users. Sentry Application Monitoring.

Fix Bugs Faster