The Application Context

The application context keeps track of the application-level data duringa request, CLI command, or other activity. Rather than passing theapplication around to each function, the current_app andg proxies are accessed instead.

This is similar to the The Request Context, which keeps track ofrequest-level data during a request. A corresponding application contextis pushed when a request context is pushed.

Purpose of the Context

The Flask application object has attributes, such asconfig, that are useful to access within views andCLI commands. However, importing the app instancewithin the modules in your project is prone to circular import issues.When using the app factory pattern orwriting reusable blueprints orextensions there won’t be an app instance toimport at all.

Flask solves this issue with the application context. Rather thanreferring to an app directly, you use the current_appproxy, which points to the application handling the current activity.

Flask automatically pushes an application context when handling arequest. View functions, error handlers, and other functions that runduring a request will have access to current_app.

Flask will also automatically push an app context when running CLIcommands registered with Flask.cli using @app.cli.command().

Lifetime of the Context

The application context is created and destroyed as necessary. When aFlask application begins handling a request, it pushes an applicationcontext and a request context. When the requestends it pops the request context then the application context.Typically, an application context will have the same lifetime as arequest.

See The Request Context for more information about how the contexts workand the full life cycle of a request.

Manually Push a Context

If you try to access current_app, or anything that uses it,outside an application context, you’ll get this error message:

  1. RuntimeError: Working outside of application context.
  2.  
  3. This typically means that you attempted to use functionality that
  4. needed to interface with the current application object in some way.
  5. To solve this, set up an application context with app.app_context().

If you see that error while configuring your application, such as wheninitializing an extension, you can push a context manually since youhave direct access to the app. Use app_context() in awith block, and everything that runs in the block will have accessto current_app.

  1. def create_app():
  2. app = Flask(__name__)
  3.  
  4. with app.app_context():
  5. init_db()
  6.  
  7. return app

If you see that error somewhere else in your code not related toconfiguring the application, it most likely indicates that you shouldmove that code into a view function or CLI command.

Storing Data

The application context is a good place to store common data during arequest or CLI command. Flask provides the g object for thispurpose. It is a simple namespace object that has the same lifetime asan application context.

Note

The g name stands for “global”, but that is referring to thedata being global within a context. The data on g is lostafter the context ends, and it is not an appropriate place to storedata between requests. Use the session or a database tostore data across requests.

A common use for g is to manage resources during a request.

  • get_X() creates resource X if it does not exist, caching itas g.X.

  • teardown_X() closes or otherwise deallocates the resource if itexists. It is registered as a teardown_appcontext()handler.

For example, you can manage a database connection using this pattern:

  1. from flask import g
  2.  
  3. def get_db():
  4. if 'db' not in g:
  5. g.db = connect_to_database()
  6.  
  7. return g.db
  8.  
  9. @app.teardown_appcontext
  10. def teardown_db():
  11. db = g.pop('db', None)
  12.  
  13. if db is not None:
  14. db.close()

During a request, every call to get_db() will return the sameconnection, and it will be closed automatically at the end of therequest.

You can use LocalProxy to make a new contextlocal from get_db():

  1. from werkzeug.local import LocalProxy
  2. db = LocalProxy(get_db)

Accessing db will call get_db internally, in the same way thatcurrent_app works.


If you’re writing an extension, g should be reserved for usercode. You may store internal data on the context itself, but be sure touse a sufficiently unique name. The current context is accessed with_app_ctx_stack.top. For more information seeFlask Extension Development.

Events and Signals

The application will call functions registered withteardown_appcontext() when the application context ispopped.

If signals_available is true, the following signals aresent: appcontext_pushed, appcontext_tearing_down, andappcontext_popped.