Flask is a popular web framework for building applications in Python. One of its key features is routing, which allows you to map URLs to functions that handle the requests.
How does routing work in Flask?
In Flask, routing is implemented using the @app.route()
decorator. This decorator is used to define the URL patterns that the application should respond to.
Here’s an example of a basic Flask app with routing:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, World!"
@app.route('/about')
def about():
return "This is the about page"
if __name__ == '__main__':
app.run()
In the above code, we define two routes: '/'
and '/about'
. The home
function is associated with the '/'
route, while the about
function is associated with the '/about'
route. When a user visits these URLs, Flask calls the corresponding function and returns the result.
Dynamic routing with variables
Flask also supports dynamic routing, in which a part of the URL can be treated as a variable. You can define route patterns with variable parts by using <variable_name>
syntax.
For example:
@app.route('/user/<username>')
def user_profile(username):
return f"Welcome to the profile page of {username}"
In the code above, the user_profile
function takes a username
parameter, which corresponds to the variable part of the URL defined in the route. So, if a user visits /user/johndoe
, Flask will pass 'johndoe'
as the username
argument to the function.
HTTP methods and routing
By default, Flask routing only handles GET requests. However, you can specify the allowed HTTP methods using the methods
parameter of the @app.route()
decorator.
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# Handle login form submission
username = request.form['username']
password = request.form['password']
# Validate credentials and log in
else:
# Display login form
return render_template('login.html')
In the example above, the login
function is mapped to /login
URL and accepts both GET and POST requests. If a GET request is made, the login form is displayed. If a POST request is made, the form data is processed to validate the credentials and log in the user.
Conclusion
Flask’s routing mechanism allows you to easily define the behavior of your web application based on the requested URLs. You can map specific URLs to corresponding functions, handle dynamic routing with variables, and specify the allowed HTTP methods for each route. Routing is a fundamental concept in Flask and understanding it is essential for building robust web applications.