Overview
The application context keeps track of application-level data during a request or CLI command. Flask automatically creates and manages this context.What is Application Context?
Fromctx.py:260-298, the AppContext class provides:
- Access to
current_appandgproxies - Application configuration and resources
- Per-request or per-command isolated state
When is it Active?
Application context is automatically pushed:- During requests - Automatically for each request
- In CLI commands - When using
flaskcommands - In tests - When using test client or context
- Manually - When you explicitly create one
The current_app Proxy
Access the current application instance:Why Use current_app?
Instead of importingapp directly:
- Works with application factories
- Supports multiple app instances
- Works in blueprints and extensions
The g Object
Fromctx.py:30-116, g is a namespace object for storing data during a context:
g Object Methods
Fromctx.py:68-103:
Creating Application Context
Manual Context Creation
In Tests
In CLI Commands
Context Lifecycle
Fromctx.py:416-517, understanding push and pop:
Teardown Functions
Run cleanup code when context is popped:Error Handling in Teardown
Teardown functions receive exceptions:Signals
Application context signals:Checking Context State
Fromctx.py:235-257:
Common Patterns
Database Connection
Request Timer
Lazy Resource Initialization
Application Context vs Request Context
| Feature | Application Context | Request Context |
|---|---|---|
| Provides | current_app, g | request, session |
| Lifetime | Request or CLI command | Request only |
| Created | Automatically or manually | Automatically |
| Use for | App config, resources | Request data |
AppContext.
Best Practices
Use g for Resources
Store request-specific resources like DB connections in g
Clean Up in Teardown
Always close resources in teardown_appcontext handlers
Avoid Direct app Import
Use current_app instead of importing app directly
Check Context State
Use has_app_context() when context may not be active
Nested Contexts
Contexts can be nested:Related Concepts
- Request Context - Request-specific context
- Application - Flask application object
- Sessions - User session management
