Contents
Understanding Flask Routing
Routing is one of the core concepts in Flask. It determines how your app responds to different URLs and what content is shown. Let’s explore how to define routes, handle different HTTP methods, create dynamic URLs, and build URLs using url_for
.
Defining Routes and Handling Different HTTP Methods (GET, POST)
In Flask, you define routes using the @app.route
decorator. A route is basically the path part of a URL (like /about
or /login
) that tells Flask which function should handle requests to that URL.
GET Requests:
By default, Flask routes handle GET requests. A GET request is used to retrieve data from the server, like displaying a webpage:
@app.route('/about')
def about():
return "This is the About page"
When someone visits http://127.0.0.1:5000/about
, Flask will display “This is the About page”.
- POST Requests:
POST requests are used to send data to the server, often from a form submission. To handle POST requests, you specify the methods in your route:
@app.route('/submit', methods=['POST'])
def submit():
data = request.form['data'] # Assuming you have a form field named 'data'
return f"Received: {data}"
Here, when a form is submitted to /submit
with a POST request, Flask processes the data and returns a response.
- Handling Both GET and POST:
You can handle both GET and POST requests in a single route by checking the request method:
@app.route('/contact', methods=['GET', 'POST'])
def contact():
if request.method == 'POST':
name = request.form['name']
return f"Thanks, {name}! We'll get back to you."
return render_template('contact.html')
In this example, visiting /contact
with a GET request will display the contact form, and submitting the form (POST request) will process the input.
Creating Dynamic URLs with Route Parameters
Sometimes you need your routes to be dynamic, meaning the URL can change depending on user input. Flask makes this easy with route parameters.
Basic Dynamic URL:
@app.route('/user/')
def show_user_profile(username):
return f'User: {username}'
Here, <username>
is a dynamic part of the URL. If you visit http://127.0.0.1:5000/user/John
, Flask will pass John
to the show_user_profile
function and display “User: John”.
Handling Multiple Parameters:
You can also have multiple dynamic parts:
@app.route('/post/')
def show_post(post_id):
return f'Post ID: {post_id}'
Here, <int:post_id>
ensures that the post_id
parameter is treated as an integer. If you visit http://127.0.0.1:5000/post/42
, Flask will pass 42
to show_post
and display “Post ID: 42”.
URL Building with url_for
Flask provides a handy function called url_for
to build URLs for your routes. This is useful for creating links in your templates or when redirecting users.
Basic URL Building:
@app.route('/home')
def home():
return "Welcome to the Home Page"
@app.route('/redirect-home')
def redirect_home():
return redirect(url_for('home'))
In this example, url_for('home')
generates the URL for the home
function (which is /home
), making it easy to link to other parts of your app without hardcoding URLs.
Passing Parameters with
url_for
:You can also pass parameters to dynamic routes:
@app.route('/greet/')
def greet(name):
return f"Hello, {name}!"
@app.route('/say-hello')
def say_hello():
return redirect(url_for('greet', name='Alice'))
Here, url_for('greet', name='Alice')
generates the URL /greet/Alice
, which the say_hello
route then redirects to.
Summary
Flask routing allows you to define how your web app responds to different URLs. You can handle various HTTP methods like GET and POST, create dynamic URLs using route parameters, and use url_for
to build URLs programmatically. Understanding these basics gives you the tools to create more complex and dynamic web applications with Flask.
Related Chapters
- What is Flask?
- Setting Up the Development Environment
- Your First Flask Application
- Understanding Flask Routing
- Rendering Templates
- Working with Forms
- Working with Databases
- User Authentication
- File Uploads and Handling
- RESTful APIs with Flask
- Application Configuration and Deployment
- Testing in Flask
- Flask Extensions
- Handling Error Pages
- Planning the Project
- Developing the Backend with Flask
- Developing the Frontend
- Deployment and Scaling