Flask Internal Objects API
Flask provides several low-level internal objects for accessing the active application context and the registration state of blueprints. Most applications do not need to use them directly.
AppContext application context
| Method/attribute | Description |
|---|---|
| AppContext(app) | Create an application context instance. Normally not created manually; use app.app_context() |
| push() | Push onto the context stack. Makes proxies such as current_app and g point to this context |
| pop(error=None) | Pop from the context stack. Executes teardown callbacks. error is the unhandled exception object |
| app | The Flask application associated with this context |
| g | The g object for this context (an _AppCtxGlobals instance) |
| url_adapter | The URL adapter (MapAdapter), used for URL building |
| request | The current request object (Request). Available only in a request context |
| session | The current Session object. Available only in a request context |
The app_ctx proxy
| property | Description |
|---|---|
| flask.globals.app_ctx | A proxy pointing to the currently active AppContext. Used internally; in most cases current_app and g are sufficient |
BlueprintSetupState
A state object during blueprint registration, usable in the record callback.
| property | Description |
|---|---|
| app | The Flask application to which the blueprint is registered |
| blueprint | The Blueprint instance being registered |
| url_prefix | The blueprint's URL prefix |
| subdomain | The blueprint's subdomain |
| url_defaults | The blueprint's URL default values |
| options | Extra options passed when registering the blueprint |
The deprecated RequestContext
Since Flask 3.2,RequestContext has been merged into AppContext. The related request_ctx proxies have also been merged into app_ctx. The old names will be removed in Flask 4.0.
Code Example
Example
from
flask
import
Flask
from
flask.
ctx
import
AppContext
app
=
Flask
(
name
)
Manually managing the application context
ctx
=
app.
app_context
(
)
ctx.
push
(
)
current_app and g are now available
from
flask
import
current_app
,
g
g.
user
=
"runoob"
Perform operations...
ctx.
pop
(
)
Triggers teardown callbacks; g is cleaned up
Using a with statement (recommended)
with
app.
app_context
(
)
:
g.
temp_data
=
42