0
# Routing and URL Handling
1
2
Flask's routing system maps URLs to view functions and provides utilities for URL generation. It supports dynamic URL segments, HTTP method restrictions, and flexible URL patterns.
3
4
## Capabilities
5
6
### Route Registration
7
8
Decorators and methods for registering URL routes with view functions.
9
10
```python { .api }
11
def route(self, rule: str, **options) -> Callable:
12
"""
13
Decorator to register a view function for a URL rule.
14
15
Args:
16
rule: URL rule string (e.g., '/user/<name>')
17
**options: Additional routing options
18
- methods: HTTP methods (default: ['GET'])
19
- endpoint: Endpoint name (defaults to function name)
20
- defaults: Default values for URL variables
21
- strict_slashes: Whether to enforce trailing slashes
22
- redirect_to: Redirect to another endpoint
23
- alias: Create URL alias
24
- host: Host matching pattern
25
- subdomain: Subdomain pattern
26
27
Returns:
28
Decorator function
29
"""
30
31
def add_url_rule(
32
self,
33
rule: str,
34
endpoint: str | None = None,
35
view_func: Callable | None = None,
36
provide_automatic_options: bool | None = None,
37
**options: Any
38
) -> None:
39
"""
40
Register a URL rule with the application.
41
42
Args:
43
rule: URL rule string
44
endpoint: Endpoint name (defaults to view function name)
45
view_func: View function to call
46
provide_automatic_options: Add OPTIONS method automatically
47
**options: Additional routing options
48
"""
49
```
50
51
### HTTP Method Decorators
52
53
Convenience decorators for specific HTTP methods.
54
55
```python { .api }
56
def get(self, rule: str, **options) -> Callable:
57
"""
58
Register a route that only accepts GET requests.
59
60
Args:
61
rule: URL rule string
62
**options: Additional routing options
63
64
Returns:
65
Decorator function
66
"""
67
68
def post(self, rule: str, **options) -> Callable:
69
"""
70
Register a route that only accepts POST requests.
71
72
Args:
73
rule: URL rule string
74
**options: Additional routing options
75
76
Returns:
77
Decorator function
78
"""
79
80
def put(self, rule: str, **options) -> Callable:
81
"""
82
Register a route that only accepts PUT requests.
83
84
Args:
85
rule: URL rule string
86
**options: Additional routing options
87
88
Returns:
89
Decorator function
90
"""
91
92
def delete(self, rule: str, **options) -> Callable:
93
"""
94
Register a route that only accepts DELETE requests.
95
96
Args:
97
rule: URL rule string
98
**options: Additional routing options
99
100
Returns:
101
Decorator function
102
"""
103
104
def patch(self, rule: str, **options) -> Callable:
105
"""
106
Register a route that only accepts PATCH requests.
107
108
Args:
109
rule: URL rule string
110
**options: Additional routing options
111
112
Returns:
113
Decorator function
114
"""
115
```
116
117
### URL Generation
118
119
Functions for generating URLs from endpoint names.
120
121
```python { .api }
122
def url_for(
123
endpoint: str,
124
*,
125
_anchor: str | None = None,
126
_method: str | None = None,
127
_scheme: str | None = None,
128
_external: bool | None = None,
129
**values: Any,
130
) -> str:
131
"""
132
Generate a URL for the given endpoint.
133
134
Args:
135
endpoint: Endpoint name (function name or custom endpoint)
136
_anchor: URL anchor/fragment
137
_method: HTTP method for URL generation
138
_scheme: URL scheme (http/https)
139
_external: Generate external URL with hostname
140
**values: Variable values for URL rule and query parameters
141
142
Returns:
143
Generated URL string
144
145
Raises:
146
BuildError: If URL cannot be built
147
"""
148
```
149
150
### URL Processing
151
152
Functions for preprocessing URLs and handling URL defaults.
153
154
```python { .api }
155
def url_value_preprocessor(self, f: Callable) -> Callable:
156
"""
157
Decorator to register URL value preprocessor.
158
159
Args:
160
f: Function that receives (endpoint, values) and can modify values
161
162
Returns:
163
The original function
164
"""
165
166
def url_defaults(self, f: Callable) -> Callable:
167
"""
168
Decorator to register URL defaults function.
169
170
Args:
171
f: Function that receives (endpoint, values) and can add defaults
172
173
Returns:
174
The original function
175
"""
176
```
177
178
### Endpoint Registration
179
180
Direct endpoint registration without URL rules.
181
182
```python { .api }
183
def endpoint(self, endpoint: str) -> Callable:
184
"""
185
Decorator to register a function as an endpoint.
186
187
Args:
188
endpoint: Endpoint name
189
190
Returns:
191
Decorator function
192
"""
193
```
194
195
### URL Adapter Creation
196
197
Methods for creating URL adapters for URL matching and building.
198
199
```python { .api }
200
def create_url_adapter(self, request: Request | None) -> MapAdapter | None:
201
"""
202
Create a URL adapter for the current request.
203
204
Args:
205
request: Current request object or None
206
207
Returns:
208
URL adapter instance or None
209
"""
210
```
211
212
## Usage Examples
213
214
### Basic Routing
215
216
```python
217
from flask import Flask
218
219
app = Flask(__name__)
220
221
# Simple route
222
@app.route('/')
223
def home():
224
return 'Home Page'
225
226
# Route with variable
227
@app.route('/user/<name>')
228
def user_profile(name):
229
return f'User: {name}'
230
231
# Route with typed variable
232
@app.route('/post/<int:post_id>')
233
def show_post(post_id):
234
return f'Post ID: {post_id}'
235
236
# Route with multiple variables
237
@app.route('/user/<name>/post/<int:post_id>')
238
def user_post(name, post_id):
239
return f'Post {post_id} by {name}'
240
```
241
242
### HTTP Methods
243
244
```python
245
from flask import Flask, request
246
247
app = Flask(__name__)
248
249
# Multiple methods
250
@app.route('/api/data', methods=['GET', 'POST', 'PUT'])
251
def api_data():
252
if request.method == 'GET':
253
return 'Getting data'
254
elif request.method == 'POST':
255
return 'Creating data'
256
elif request.method == 'PUT':
257
return 'Updating data'
258
259
# Method-specific decorators
260
@app.get('/items')
261
def get_items():
262
return 'Getting items'
263
264
@app.post('/items')
265
def create_item():
266
return 'Creating item'
267
268
@app.put('/items/<int:item_id>')
269
def update_item(item_id):
270
return f'Updating item {item_id}'
271
272
@app.delete('/items/<int:item_id>')
273
def delete_item(item_id):
274
return f'Deleting item {item_id}'
275
```
276
277
### URL Generation
278
279
```python
280
from flask import Flask, url_for, redirect
281
282
app = Flask(__name__)
283
284
@app.route('/')
285
def home():
286
return 'Home'
287
288
@app.route('/user/<name>')
289
def user_profile(name):
290
return f'User: {name}'
291
292
@app.route('/admin')
293
def admin():
294
# Redirect to user profile
295
return redirect(url_for('user_profile', name='admin'))
296
297
@app.route('/nav')
298
def navigation():
299
# Generate URLs
300
home_url = url_for('home')
301
user_url = url_for('user_profile', name='john')
302
admin_url = url_for('admin')
303
304
return f'''
305
<a href="{home_url}">Home</a><br>
306
<a href="{user_url}">John's Profile</a><br>
307
<a href="{admin_url}">Admin</a>
308
'''
309
```
310
311
### Advanced Routing Options
312
313
```python
314
from flask import Flask
315
316
app = Flask(__name__)
317
318
# Route with defaults
319
@app.route('/blog/')
320
@app.route('/blog/<int:page>')
321
def blog(page=1):
322
return f'Blog page {page}'
323
324
# Route with custom endpoint name
325
@app.route('/about', endpoint='about_page')
326
def about_us():
327
return 'About Us'
328
329
# Route with host matching
330
@app.route('/api/status', host='api.example.com')
331
def api_status():
332
return 'API Status'
333
334
# Route with subdomain
335
@app.route('/', subdomain='blog')
336
def blog_index():
337
return 'Blog Home'
338
339
# Strict slashes
340
@app.route('/path', strict_slashes=True)
341
def strict_path():
342
return 'Strict path (no trailing slash allowed)'
343
344
@app.route('/flexible/', strict_slashes=False)
345
def flexible_path():
346
return 'Flexible path (trailing slash optional)'
347
```
348
349
### URL Converters
350
351
```python
352
from flask import Flask
353
from werkzeug.routing import BaseConverter
354
355
app = Flask(__name__)
356
357
# Built-in converters
358
@app.route('/string/<string:text>') # Default converter
359
def show_string(text):
360
return f'String: {text}'
361
362
@app.route('/int/<int:number>')
363
def show_int(number):
364
return f'Integer: {number}'
365
366
@app.route('/float/<float:number>')
367
def show_float(number):
368
return f'Float: {number}'
369
370
@app.route('/path/<path:filepath>')
371
def show_path(filepath):
372
return f'Path: {filepath}'
373
374
@app.route('/uuid/<uuid:id>')
375
def show_uuid(id):
376
return f'UUID: {id}'
377
378
# Custom converter
379
class ListConverter(BaseConverter):
380
def to_python(self, value):
381
return value.split(',')
382
383
def to_url(self, values):
384
return ','.join(BaseConverter.to_url(value) for value in values)
385
386
app.url_map.converters['list'] = ListConverter
387
388
@app.route('/tags/<list:tags>')
389
def show_tags(tags):
390
return f'Tags: {", ".join(tags)}'
391
```
392
393
### URL Processing
394
395
```python
396
from flask import Flask, g
397
398
app = Flask(__name__)
399
400
@app.url_value_preprocessor
401
def pull_lang_code(endpoint, values):
402
if values is not None:
403
g.lang_code = values.pop('lang_code', None)
404
405
@app.url_defaults
406
def inject_lang_code(endpoint, values):
407
if 'lang_code' in values or not g.get('lang_code'):
408
return
409
if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
410
values['lang_code'] = g.lang_code
411
412
@app.route('/<lang_code>/')
413
@app.route('/<lang_code>/page')
414
def index(lang_code):
415
return f'Language: {lang_code}'
416
```
417
418
### Programmatic Route Registration
419
420
```python
421
from flask import Flask
422
423
app = Flask(__name__)
424
425
def hello_world():
426
return 'Hello World!'
427
428
def user_profile(username):
429
return f'User: {username}'
430
431
# Register routes programmatically
432
app.add_url_rule('/', 'index', hello_world)
433
app.add_url_rule('/user/<username>', 'profile', user_profile)
434
435
# With options
436
app.add_url_rule(
437
'/api/data',
438
'api_data',
439
lambda: 'API Data',
440
methods=['GET', 'POST']
441
)
442
```