Flask is a popular web framework in Python that is known for its simplicity and flexibility. One of its main features is routing, which lets us map URLs to specific functions in our code. In this detailed guide, we will explore Flask routing, understand its features, and see examples to make things clear. We will also touch upon some advanced topics to give you a comprehensive understanding.
We will also touch upon some advanced topics to give you a comprehensive understanding. For more details on what Flask is, you can visit our guide on Flask.
What is Flask Routing?
Routing in Flask is the process of matching URLs to the functions that should handle them. When a user visits a URL, Flask runs the associated function and returns the response. This is essential for building dynamic web applications.
Setting Up Flask
First, let’s set up a basic Flask application. Make sure you have Flask installed. You can install it using pip:
pip install flask
Now, create a file called app.py
and add the following code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Welcome to the Home Page!"
if __name__ == '__main__':
app.run(debug=True)
In this example:
- We create a Flask application by creating an instance of the
Flask
class. - The
@app.route('/')
decorator maps the root URL (/
) to thehome
function. - When someone visits the root URL, the
home
function runs and returns “Welcome to the Home Page!”.
Run the app by typing python app.py
in your terminal and visiting http://127.0.0.1:5000/
in your browser.
Flask Dynamic Routing
Flask allows us to create dynamic routes that can accept parameters. For example:
@app.route('/user/<username>')
def show_user_profile(username):
return f"User: {username}"
Here, <username>
is a placeholder for any value that comes after /user/
in the URL. For instance, visiting /user/Alice
will display “User: Alice”.
Flask Routes in a Separate File
For better organization, especially in larger projects, you can define routes in a separate file and import them into your main application. Create a separate file, say routes.py
:
# routes.py
from flask import Blueprint
main_bp = Blueprint('main', __name__)
@main_bp.route('/')
def home():
return "Welcome to the Home Page!"
Then, in your main application file, import and register the Blueprint:
# app.py
from flask import Flask
from routes import main_bp
app = Flask(__name__)
app.register_blueprint(main_bp)
if __name__ == '__main__':
app.run(debug=True)
Flask Blueprint Route
Blueprints in Flask are a way to organize your application into smaller and more manageable parts. They allow you to group related routes and views together. This is especially useful for large applications where different parts of the application might need to be separated logically.
For example, you might want to separate the admin routes from the user routes. Here’s how you can do it:
Create a file named admin.py
:
# admin.py
from flask import Blueprint
admin_bp = Blueprint('admin', __name__)
@admin_bp.route('/dashboard')
def dashboard():
return "Admin Dashboard"
In your main application file, import and register the Blueprint:
# app.py
from flask import Flask
from admin import admin_bp
app = Flask(__name__)
app.register_blueprint(admin_bp, url_prefix='/admin')
if __name__ == '__main__':
app.run(debug=True)
In this example:
- We create a Blueprint called
admin_bp
. - We define a route
/dashboard
in the Blueprint. - We register the Blueprint with the main app, prefixing all its routes with
/admin
.
Flask App Route Methods
By default, Flask routes handle GET requests. To handle other methods like POST, PUT, DELETE, etc., use the methods
parameter:
@app.route('/submit', methods=['POST'])
def submit():
return "Form Submitted!"
Flask PUT Example
The PUT method is used to update existing resources. In Flask, you can define a route to handle PUT requests using the methods
parameter in the @app.route
decorator. Here is an example of a route that handles PUT requests:
@app.route('/update/<int:item_id>', methods=['PUT'])
def update_item(item_id):
return f"Item {item_id} has been updated"
In this example:
- The route
/update/<int:item_id>
is defined to handle PUT requests. - The
item_id
parameter is extracted from the URL and passed to theupdate_item
function. - When a PUT request is made to
/update/123
, the function will return “Item 123 has been updated”.
Flask Route Decorator
The @app.route
decorator is used to bind a function to a URL. This decorator tells Flask to call the associated function when the specified URL is accessed. Here’s a basic example:
@app.route('/')
def home():
return "Welcome to the Home Page!"
In this example:
- The
@app.route('/')
decorator binds thehome
function to the root URL (/
). - When someone visits the root URL, the
home
function runs and returns “Welcome to the Home Page!”.
Flask Route Regex
You can use regular expressions in Flask routes to create more flexible patterns. Regular expressions allow you to define complex URL patterns that can match a wide range of input values. Here’s an example:
from flask import Flask
import re
app = Flask(__name__)
@app.route('/item/<regex("[a-z]{3}-[0-9]{3}"):item_code>')
def show_item(item_code):
return f"Item Code: {item_code}"
In this example:
- We use the
regex
converter to define a route that matches a specific pattern. - The pattern
[a-z]{3}-[0-9]{3}
matches any string with three lowercase letters followed by a hyphen and three digits. - If the URL matches this pattern, the
item_code
parameter is passed to theshow_item
function.
Flask Route Parameter
Flask allows multiple URL parameters, which can be very useful for dynamic web pages:
@app.route('/profile/<username>/<int:age>')
def profile(username, age):
return f"Username: {username}, Age: {age}"
In this route, visiting /profile/Alice/30
will display “Username: Alice, Age: 30”.
Flask Route Optional Parameter
You can also create routes with optional parameters using default values:
@app.route('/article/', defaults={'page': 1})
@app.route('/article/page/<int:page>')
def article(page):
return f"Showing page {page} of the article"
Visiting /article/
and /article/page/2
will display “Showing page 1 of the article” and “Showing page 2 of the article” respectively.
Flask Multiple Routes Same Function
A single function can be associated with multiple routes:
@app.route('/')
@app.route('/home')
def home():
return "Welcome to the Home Page!"
In this example:
- The
home
function is bound to both the root URL (/
) and the/home
URL. - Visiting either
/
or/home
will execute thehome
function and return “Welcome to the Home Page!”.
Flask Route Multiple Parameters
You can also handle multiple parameters in a route:
@app.route('/user/<username>/posts/<int:post_id>')
def show_user_post(username, post_id):
return f"User: {username}, Post ID: {post_id}"
In this route, visiting /user/Alice/posts/5
will display “User: Alice, Post ID: 5”.
Conclusion
Flask routing is a powerful and flexible feature that helps map URLs to functions, making web applications dynamic and interactive. From basic routing to advanced topics like custom converters and middleware, Flask provides all the tools needed to build robust web applications.
For more detailed information, you can refer to the official Flask documentation.
Comments