Routing is an essential feature of any web framework, including Flask. In Flask, routing allows you to map URLs to functions that handle them. When a user makes a request to a URL, Flask uses the routing information to determine which function should handle the request.
In this article, we’ll cover the basics of Flask routing, including how to define routes, use parameters, and handle errors.
Defining Routes
In Flask, you define routes using the @app.route()
decorator. The decorator tells Flask which URL should trigger your function. Here’s an example:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
In this example, we’re defining a route for the root URL (/
). When a user visits the root URL, Flask calls the hello_world()
function, which returns the “Hello, World!” string.
You can define routes for other URLs by specifying the URL path in the @app.route()
decorator. For example:
@app.route('/about')
def about():
return 'This is the About page.'
In this example, we’re defining a route for the /about
URL. When a user visits the /about
URL, Flask calls the about()
function, which returns the “This is the About page.” string.
Passing Parameters
You can pass parameters to a route by enclosing them in < >
brackets in the URL path. For example:
@app.route('/user/<username>')
def show_user_profile(username):
return f'User {username}'
In this example, we’re defining a route for the /user/<username>
URL. When a user visits a URL that matches this pattern, Flask calls the show_user_profile()
function, passing the value of <username>
as a parameter. The function returns a string that includes the username.
You can also specify the type of parameter using a converter. For example:
@app.route('/post/<int:post_id>')
def show_post(post_id):
return f'Post {post_id}'
In this example, we’re defining a route for the /post/<int:post_id>
URL. The <int>
converter tells Flask to only match integer values for post_id
. If a user visits a URL that matches this pattern, Flask calls the show_post()
function, passing the integer value of post_id
as a parameter.
Handling Errors
In Flask, you can define error handlers for HTTP errors such as 404 (not found) or 500 (server error). To define an error handler, you use the @app.errorhandler()
decorator. For example:
@app.errorhandler(404)
def page_not_found(error):
return 'Sorry, the page you requested could not be found.'
In this example, we’re defining an error handler for the 404 HTTP error. When a user requests a URL that Flask cannot find, Flask calls the page_not_found()
function, which returns a string with an error message.
Conclusion
Flask routing is a powerful feature that allows you to map URLs to functions in your web application. With Flask routing, you can handle user requests, pass parameters, and handle errors. By understanding Flask routing, you can create robust web applications that are easy to maintain and scale