Routing in Flask
Routing in Flask is the process of mapping URLs to specific functions in your application. This allows you to create different pages or endpoints that users can access. Understanding routing is crucial for building a functional web application.
Key Concepts
1. Route Decorators
Flask uses route decorators to define the URLs that should trigger specific functions. The decorator @app.route()
is used to bind a function to a URL.
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return "Welcome to the Home Page!"
In this example, the @app.route('/')
decorator maps the root URL ("/") to the home()
function, which returns a simple welcome message.
2. Dynamic Routing
Flask allows you to create dynamic routes by using variable sections in the URL. These sections can be passed as arguments to the function.
@app.route('/user/<username>') def show_user(username): return f"User: {username}"
Here, the <username>
part of the URL is a variable that gets passed to the show_user()
function. When a user accesses /user/john
, the function will return "User: john".
3. HTTP Methods
Flask supports different HTTP methods like GET, POST, PUT, DELETE, etc. You can specify which methods a route should handle using the methods
parameter in the route decorator.
@app.route('/submit', methods=['POST']) def submit(): data = request.form['data'] return f"You submitted: {data}"
In this example, the /submit
route only accepts POST requests. The request.form['data']
accesses the data sent in the form.
4. URL Building
Flask provides a url_for()
function to generate URLs for specific functions. This is useful for avoiding hardcoding URLs in your application.
from flask import Flask, url_for app = Flask(__name__) @app.route('/') def home(): return "Home Page" @app.route('/about') def about(): return "About Page" @app.route('/links') def links(): home_url = url_for('home') about_url = url_for('about') return f"Home: {home_url}, About: {about_url}"
In this example, url_for('home')
generates the URL for the home()
function, and url_for('about')
generates the URL for the about()
function.
By mastering these concepts, you can create a robust and flexible routing system in your Flask application, enabling you to build dynamic and interactive web pages.