What is Routing?
Routing is the process of binding a URL to a specific Python function. In Flask, this is handled primarily through the @app.route() decorator. When a user visits a specific path, Flask identifies the associated function (called a 'View Function') and executes it to return a response.
- Basic and Dynamic Routing
Static routes are simple, but dynamic routes allow you to capture values from the URL and pass them as arguments to your function. This is vital for resources like user profiles or blog posts.
- Variable Converters
By default, dynamic segments are treated as strings. You can use converters to ensure the data is of a specific type (int, float, path, uuid) before the function is even called. If the type doesn't match, Flask returns a 404 error.
- HTTP Methods
By default, routes only respond to GET requests. To build a RESTful API, you must explicitly list the methods the route should handle.
- URL Building with url_for
Never hardcode URLs in your application. Use url_for() to generate URLs based on the function name. This ensures that if you change the URL path in the decorator, all your links automatically update.
Routing Summary
| Converter | Description | Example |
|---|---|---|
| string | Default (accepts any text without slashes) | /page/<name> |
| int | Accepts positive integers | /user/<int:id> |
| float | Accepts positive floating point values | /price/<float:val> |
| path | Like string but accepts slashes | /storage/<path:file> |
| uuid | Accepts UUID strings | /transaction/<uuid:id> |