A Flask extension for handling Cross Origin Resource Sharing (CORS), making cross-origin AJAX possible
npx @tessl/cli install tessl/pypi-flask-cors@5.0.00
# Flask-CORS
1
2
A Flask extension for handling Cross Origin Resource Sharing (CORS), making cross-origin AJAX possible. Flask-CORS provides comprehensive CORS support that can be applied globally to all routes, selectively to specific resources and origins, or individually to routes using decorators.
3
4
## Package Information
5
6
- **Package Name**: Flask-Cors
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install flask-cors`
10
11
## Core Imports
12
13
```python
14
from flask_cors import CORS, cross_origin
15
```
16
17
For version information:
18
19
```python
20
from flask_cors import __version__
21
```
22
23
## Basic Usage
24
25
### Application-wide CORS
26
27
```python
28
from flask import Flask
29
from flask_cors import CORS
30
31
app = Flask(__name__)
32
CORS(app) # Enable CORS for all routes and origins
33
34
@app.route("/")
35
def hello():
36
return "Hello, cross-origin-world!"
37
```
38
39
### Resource-specific CORS
40
41
```python
42
from flask import Flask
43
from flask_cors import CORS
44
45
app = Flask(__name__)
46
CORS(app, resources={r"/api/*": {"origins": "*"}})
47
48
@app.route("/api/v1/users")
49
def list_users():
50
return "user example"
51
```
52
53
### Route-specific CORS with decorator
54
55
```python
56
from flask import Flask
57
from flask_cors import cross_origin
58
59
app = Flask(__name__)
60
61
@app.route("/")
62
@cross_origin()
63
def hello():
64
return "Hello, cross-origin-world!"
65
```
66
67
## Architecture
68
69
Flask-CORS follows the Flask extension pattern with two main approaches:
70
71
- **Extension Pattern**: The `CORS` class integrates with Flask's application context and uses after_request handlers to automatically add CORS headers to responses
72
- **Decorator Pattern**: The `cross_origin` decorator wraps individual route functions to add CORS headers on a per-route basis
73
- **Configuration Hierarchy**: Settings are resolved in order: resource-level → keyword arguments → app configuration → defaults
74
75
The extension automatically handles:
76
- Preflight OPTIONS requests
77
- Origin validation and matching (strings, regexes, wildcards)
78
- Header validation and filtering
79
- Credential handling and security enforcement
80
- Exception interception for consistent CORS headers
81
82
## Capabilities
83
84
### CORS Extension
85
86
Application-wide CORS configuration using the CORS class. Supports global settings, resource-specific configurations, and automatic handling of preflight requests and exception responses.
87
88
```python { .api }
89
class CORS:
90
def __init__(
91
self,
92
app=None,
93
resources=r"/*",
94
origins="*",
95
methods=None,
96
expose_headers=None,
97
allow_headers="*",
98
supports_credentials=False,
99
max_age=None,
100
send_wildcard=False,
101
vary_header=True,
102
allow_private_network=False,
103
intercept_exceptions=True,
104
always_send=True,
105
**kwargs
106
): ...
107
108
def init_app(self, app, **kwargs): ...
109
```
110
111
[CORS Extension](./cors-extension.md)
112
113
### Cross-Origin Decorator
114
115
Route-specific CORS configuration using the cross_origin decorator. Provides fine-grained control over CORS settings for individual routes with automatic OPTIONS handling.
116
117
```python { .api }
118
def cross_origin(
119
origins="*",
120
methods=None,
121
expose_headers=None,
122
allow_headers="*",
123
supports_credentials=False,
124
max_age=None,
125
send_wildcard=False,
126
vary_header=True,
127
automatic_options=True,
128
allow_private_network=False,
129
always_send=True,
130
**kwargs
131
): ...
132
```
133
134
[Cross-Origin Decorator](./cross-origin-decorator.md)
135
136
## Types
137
138
```python { .api }
139
from typing import Union, List, Dict, Pattern, Any
140
from datetime import timedelta
141
142
# Common type aliases used throughout the API
143
Origins = Union[str, List[str], Pattern[str], List[Pattern[str]]]
144
Methods = Union[str, List[str]]
145
Headers = Union[str, List[str], Pattern[str], List[Pattern[str]]]
146
MaxAge = Union[int, float, timedelta, str]
147
Resources = Union[str, List[str], Dict[str, Dict[str, Any]], Pattern[str]]
148
```
149
150
## Constants
151
152
```python { .api }
153
__version__: str # Package version (e.g., "5.0.0")
154
155
# Default HTTP methods allowed for CORS
156
ALL_METHODS = ["GET", "HEAD", "POST", "OPTIONS", "PUT", "PATCH", "DELETE"]
157
```
158
159
## Configuration
160
161
All CORS options can be configured through:
162
163
1. **Direct parameters** to `CORS()` or `cross_origin()`
164
2. **Flask app configuration** using `CORS_*` prefixed keys
165
3. **Resource-specific dictionaries** (for CORS extension only)
166
167
### Flask Configuration Keys
168
169
```python
170
CORS_ORIGINS # Allowed origins
171
CORS_METHODS # Allowed methods
172
CORS_ALLOW_HEADERS # Allowed request headers
173
CORS_EXPOSE_HEADERS # Headers exposed to client
174
CORS_SUPPORTS_CREDENTIALS # Allow credentials
175
CORS_MAX_AGE # Preflight cache time
176
CORS_SEND_WILDCARD # Send '*' instead of specific origin
177
CORS_AUTOMATIC_OPTIONS # Handle OPTIONS automatically
178
CORS_VARY_HEADER # Include Vary: Origin header
179
CORS_RESOURCES # Resource patterns and options
180
CORS_INTERCEPT_EXCEPTIONS # Apply CORS to exception handlers
181
CORS_ALWAYS_SEND # Send headers even without Origin
182
CORS_ALLOW_PRIVATE_NETWORK # Allow private network access
183
```
184
185
## Error Handling
186
187
Flask-CORS includes comprehensive logging support for troubleshooting CORS issues:
188
189
```python
190
import logging
191
logging.getLogger('flask_cors').level = logging.DEBUG
192
```
193
194
Common exceptions:
195
- `ValueError`: Raised when `supports_credentials=True` is used with wildcard origins (`'*'`)
196
197
## Security Considerations
198
199
- **Credentials**: By default, cookie submission across domains is disabled for security
200
- **Wildcard Origins**: Cannot be used with `supports_credentials=True` per CORS specification
201
- **Private Network**: Modern browsers require explicit permission for private network access
202
- **Origin Validation**: Supports exact matches, regex patterns, and case-insensitive comparison
203
- **CSRF Protection**: Consider implementing CSRF protection when enabling credentials