0
# Context and Globals
1
2
Flask provides context management and global objects for accessing application and request data throughout the request lifecycle.
3
4
## Capabilities
5
6
### Context Management Functions
7
8
```python { .api }
9
def has_app_context() -> bool:
10
"""Check if there is an active application context."""
11
12
def has_request_context() -> bool:
13
"""Check if there is an active request context."""
14
15
def copy_current_request_context(f: Callable) -> Callable:
16
"""Copy the current request context for use in a different thread."""
17
18
def after_this_request(f: Callable) -> Callable:
19
"""Register a function to run after the current request."""
20
```
21
22
### Global Proxy Objects
23
24
```python { .api }
25
current_app: LocalProxy # Current Flask application
26
request: LocalProxy # Current request object
27
session: LocalProxy # Current session
28
g: LocalProxy # Application context global object
29
```
30
31
### Context Classes
32
33
```python { .api }
34
class AppContext:
35
"""Application context for Flask applications."""
36
37
class RequestContext:
38
"""Request context for handling individual requests."""
39
```
40
41
## Usage Examples
42
43
### Basic Context Usage
44
45
```python
46
from flask import Flask, current_app, request, g
47
48
app = Flask(__name__)
49
50
@app.before_request
51
def before_request():
52
g.user_id = request.headers.get('X-User-ID')
53
54
@app.route('/context-info')
55
def context_info():
56
return {
57
'app_name': current_app.name,
58
'request_method': request.method,
59
'user_id': g.get('user_id')
60
}
61
```