0
# CORS Extension
1
2
The CORS class provides application-wide Cross-Origin Resource Sharing configuration for Flask applications. It integrates with Flask's request/response cycle to automatically add appropriate CORS headers based on configurable rules and resource patterns.
3
4
## Capabilities
5
6
### CORS Class Initialization
7
8
Creates a CORS extension instance that can be bound to a Flask application either during instantiation or later using the application factory pattern.
9
10
```python { .api }
11
class CORS:
12
def __init__(
13
self,
14
app=None,
15
resources=r"/*",
16
origins="*",
17
methods=None,
18
expose_headers=None,
19
allow_headers="*",
20
supports_credentials=False,
21
max_age=None,
22
send_wildcard=False,
23
vary_header=True,
24
allow_private_network=False,
25
intercept_exceptions=True,
26
always_send=True,
27
**kwargs
28
):
29
"""
30
Initialize Cross Origin Resource sharing for the application.
31
32
Parameters:
33
- app: Flask application instance (optional)
34
- resources: Resource patterns to match (dict, list, string, or regex)
35
- origins: Allowed origins (string, list, or regex patterns)
36
- methods: Allowed HTTP methods (list or string)
37
- expose_headers: Headers safe to expose to CORS API (list or string)
38
- allow_headers: Headers allowed in requests (list, string, or regex)
39
- supports_credentials: Allow authenticated requests (bool)
40
- max_age: Cache time for preflight requests (timedelta, int, or string)
41
- send_wildcard: Send '*' instead of specific origin (bool)
42
- vary_header: Include Vary: Origin header (bool)
43
- allow_private_network: Allow private network access (bool, default: False)
44
- intercept_exceptions: Apply CORS to exception handlers (bool)
45
- always_send: Send CORS headers even without Origin header (bool)
46
"""
47
```
48
49
### Application Factory Pattern
50
51
Binds the CORS extension to a Flask application, supporting the application factory pattern where the app is created after the extension.
52
53
```python { .api }
54
def init_app(self, app, **kwargs):
55
"""
56
Initialize the CORS extension with a Flask application.
57
58
Parameters:
59
- app: Flask application instance
60
- **kwargs: Additional CORS options (same as __init__)
61
"""
62
```
63
64
## Usage Examples
65
66
### Global CORS Configuration
67
68
```python
69
from flask import Flask
70
from flask_cors import CORS
71
72
app = Flask(__name__)
73
CORS(app) # Enable CORS for all routes with default settings
74
75
@app.route("/api/data")
76
def get_data():
77
return {"message": "Hello from CORS-enabled endpoint"}
78
```
79
80
### Resource-Specific Configuration
81
82
```python
83
from flask import Flask
84
from flask_cors import CORS
85
86
app = Flask(__name__)
87
88
# Configure different CORS settings for different URL patterns
89
CORS(app, resources={
90
r"/api/*": {"origins": ["https://frontend.example.com"]},
91
r"/public/*": {"origins": "*"},
92
r"/admin/*": {
93
"origins": ["https://admin.example.com"],
94
"supports_credentials": True
95
}
96
})
97
98
@app.route("/api/users")
99
def api_users():
100
return {"users": []}
101
102
@app.route("/public/info")
103
def public_info():
104
return {"info": "public data"}
105
106
@app.route("/admin/stats")
107
def admin_stats():
108
return {"stats": "sensitive data"}
109
```
110
111
### Application Factory Pattern
112
113
```python
114
from flask import Flask
115
from flask_cors import CORS
116
117
cors = CORS()
118
119
def create_app():
120
app = Flask(__name__)
121
122
# Configure CORS with the application
123
cors.init_app(app, resources={
124
r"/api/*": {"origins": ["https://trusted-domain.com"]}
125
})
126
127
return app
128
129
app = create_app()
130
```
131
132
### Advanced Origins Configuration
133
134
```python
135
import re
136
from flask import Flask
137
from flask_cors import CORS
138
139
app = Flask(__name__)
140
141
# Mixed origins configuration with strings and regex patterns
142
CORS(app, resources={
143
r"/api/*": {
144
"origins": [
145
"https://example.com", # Exact match
146
"http://localhost:3000", # Development server
147
r"https://.*\.example\.com", # Subdomain regex
148
re.compile(r"https://app\d+\.example\.com") # Compiled regex
149
]
150
}
151
})
152
```
153
154
### Credentials and Security
155
156
```python
157
from flask import Flask
158
from flask_cors import CORS
159
160
app = Flask(__name__)
161
162
# Enable credentials for trusted origins only
163
CORS(app, resources={
164
r"/api/auth/*": {
165
"origins": ["https://trusted-frontend.com"],
166
"supports_credentials": True,
167
"allow_headers": ["Content-Type", "Authorization"]
168
}
169
})
170
171
@app.route("/api/auth/login", methods=["POST"])
172
def login():
173
# This endpoint will accept cookies and credentials
174
return {"token": "auth-token"}
175
```
176
177
### Configuration Priority
178
179
Settings are resolved in the following order (last wins):
180
181
1. Default settings
182
2. App-level Flask configuration (CORS_*)
183
3. CORS constructor keyword arguments
184
4. Resource-specific options
185
5. init_app keyword arguments
186
187
```python
188
from flask import Flask
189
from flask_cors import CORS
190
191
app = Flask(__name__)
192
193
# App-level configuration
194
app.config['CORS_ORIGINS'] = ['https://default.com']
195
196
# Constructor arguments override app config
197
cors = CORS(origins=['https://constructor.com'])
198
199
# Resource-specific settings override constructor
200
cors.init_app(app, resources={
201
r"/specific/*": {"origins": ["https://specific.com"]}
202
})
203
```
204
205
## Resource Pattern Matching
206
207
Resource patterns support multiple formats for flexible URL matching:
208
209
### String Patterns
210
211
```python
212
CORS(app, resources={
213
"/exact/path": {"origins": "*"}, # Exact match
214
r"/api/*": {"origins": "*"}, # Wildcard pattern
215
r"/users/\d+": {"origins": "*"} # Regex pattern
216
})
217
```
218
219
### Compiled Regex
220
221
```python
222
import re
223
224
CORS(app, resources={
225
re.compile(r"/api/v\d+/.*"): {"origins": "*"}
226
})
227
```
228
229
### List of Patterns
230
231
```python
232
CORS(app, resources=[
233
r"/api/*",
234
r"/public/*"
235
]) # Uses app-wide configuration for all patterns
236
```
237
238
## Error Handling
239
240
The CORS extension automatically handles common error scenarios:
241
242
- **Invalid Origins**: Non-matching origins are rejected silently
243
- **Missing Headers**: Required CORS headers are added automatically
244
- **Preflight Requests**: OPTIONS requests are handled automatically
245
- **Exception Responses**: CORS headers are added to error responses (if `intercept_exceptions=True`)
246
247
## Performance Considerations
248
249
- **Pattern Matching**: Patterns are sorted by length (longest first) for optimal matching
250
- **Caching**: Preflight responses can be cached using `max_age` parameter
251
- **Header Optimization**: Only necessary headers are added to responses