
In Flask, routing refers to the process of mapping URLs to functions that should be executed when those URLs are requested. Flask uses a system of “routes” to determine which function to execute for a given URL.
To define a route in Flask, you use the @app.route()
decorator. This decorator takes the URL pattern as an argument, and specifies the function that should be executed when that URL is requested. Here is an example of how to define a route in Flask:
@app.route('/')
def index():
return 'Hello, world!'
In this example, the index()
function is executed whenever the root URL (/
) is requested. The function returns a simple string, which is then displayed on the page.
- Flask Variable Rules
- How To Redirect In Flask
- How To Build URLs In Flask
- Using Different HTTP Methods
- Flask Routing Summary
Flask routes can also include wildcards, which allow you to match URLs with variable components. For example, you could define a route that matches URLs of the form /user/<username>
, where <username>
is a variable that can be any string. Here is an example of how to define a route with a wildcard:
@app.route('/user/<username>')
def show_user(username):
return 'Hello, {}!'.format(username)
In this example, the show_user()
function is executed whenever a URL of the form /user/<username>
is requested. The username
parameter is set to the value of the wildcard in the URL, so the function can use it to display personalized content.
Flask Variable Rules
In Flask, “variable rules” are used to define wildcards in your route patterns. These wildcards allow you to match URLs with variable components, so that your routes can handle URLs with different values in certain parts.
To use a variable rule in a Flask route, you include the wildcard in the route pattern using angle brackets (<>
). The wildcard name should be included inside the brackets, and can be any string that consists only of letters, numbers, and underscores. Here is an example of a Flask route with a variable rule:
@app.route('/user/<username>')
def show_user(username):
return 'Hello, {}!'.format(username)
In this example, the route pattern includes a wildcard called username
, which matches any string of letters, numbers, and underscores. When a URL of the form /user/<username>
is requested, the value of the username
wildcard is passed as an argument to the show_user()
function.
You can also specify the type of the wildcard by using a converter, which is a string that follows the wildcard name and specifies the type of the variable. Flask includes several built-in converters for common types, such as int
for integers and float
for floating-point numbers. Here is an example of a Flask route with a variable rule and a converter:
@app.route('/post/<int:post_id>')
def show_post(post_id):
return 'Post #{}'.format(post_id)
In this example, the route pattern includes a wildcard called post_id
, which is an integer type. When a URL of the form /post/<post_id>
is requested, the value of the post_id
wildcard is passed as an argument to the show_post()
function. The post_id
variable will be an integer, so you can use it directly in your code without needing to convert it.
How To Redirect In Flask
In Flask, redirection refers to the process of sending the user to a different URL from the one they originally requested. Flask provides a convenient way to perform redirection using the redirect()
function from the flask
module.
To use the redirect()
function, you call it with the URL you want to redirect the user to. Here is an example of how to use the redirect()
function in a Flask route:
@app.route('/login')
def login():
if not session.get('logged_in'):
return redirect('/login-form')
else:
return redirect('/')
In this example, the login()
function is executed when the /login
URL is requested. If the user is not logged in, the function redirects them to the /login-form
URL. Otherwise, the user is redirected to the root URL (/
).
You can also use the redirect()
function to redirect the user to a different route in your Flask application. To do this, you use the name of the route instead of the URL. Here is an example of how to redirect the user to a different route in Flask:
@app.route('/login')
def login():
if not session.get('logged_in'):
return redirect(url_for('login_form'))
else:
return redirect(url_for('index'))
In this example, the login()
function is executed when the /login
URL is requested. If the user is not logged in, the function redirects them to the login_form()
route. Otherwise, the user is redirected to the index()
route.
How To Build URLs In Flask
In Flask, you can build URLs using the url_for()
function from the flask
module. This function takes the name of a route or view function as an argument, and returns the URL for that route or view.
Here is an example of how to use the url_for()
function in a Flask template:
<a href="{{ url_for('index') }}">Home</a>
In this example, the url_for()
function is used to build a URL for the index()
route. The generated URL is then used in an <a>
tag to create a link to the home page.
You can also pass arguments to the url_for()
function to include variables in the generated URL. For example, if you have a route with a wildcard that matches URLs of the form /user/<username>
, you can use the url_for()
function to generate URLs for specific users:
<a href="{{ url_for('show_user', username='johndoe') }}">John Doe</a>
In this example, the url_for()
function is called with the show_user
route name and the username
argument. The generated URL will be /user/johndoe
, which will match the show_user
route and pass the johndoe
value to the route’s function as the username
argument.
Using Different HTTP Methods
In Flask, you can specify which HTTP methods are allowed for a given route by using the methods
parameter of the @app.route()
decorator. This parameter takes a list of HTTP method names, and only allows those methods for the route.
Here is an example of how to use the methods
parameter to specify which HTTP methods are allowed for a route:
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# Handle the login form submission
pass
else:
# Show the login form
pass
In this example, the login()
function is executed when the /login
URL is requested, but only if the request method is GET
or POST
. If the request method is GET
, the function shows the login form. If the request method is POST
, the function handles the login form submission.
You can also use the methods
parameter to restrict a route to a single HTTP method. For example, if you want to allow only POST
requests for a given route, you can use the methods
parameter as follows:
@app.route('/login', methods=['POST'])
def login():
# Handle the login form submission
pass
In this example, the login()
function is executed only if the request method is POST
. Any other request method, such as GET
or PUT
, will result in a “Method Not Allowed” error.
Flask Routing Summary
In Flask, routing refers to the process of mapping URLs to functions that should be executed when those URLs are requested. Flask uses a system of “routes” to determine which function to execute for a given URL.
To define a route in Flask, you use the @app.route()
decorator. This decorator takes the URL pattern as an argument, and specifies the function that should be executed when that URL is requested. You can also use variable rules and converters in your route patterns to match URLs with variable components.
Flask also provides the redirect()
function, which allows you to redirect the user to a different URL or route. And the url_for()
function allows you to build URLs for different routes and views in your application.
Additionally, the methods
parameter of the @app.route()
decorator allows you to specify which HTTP methods are allowed for a given route. This can be useful for creating routes that respond to different types of requests in different ways.
Overall, Flask’s routing system provides a powerful and flexible way to handle incoming requests and generate responses. It is an essential part of Flask’s request-response cycle, and is a key feature of the framework.
- How Flask Routing Works – vegibit (vegibit.com)
- Quickstart — Flask Documentation (2.2.x) (flask.palletsprojects.com)
- Flask Tutorial: Routes – Python Tutorial – pythonbasics.org (pythonbasics.org)
- App Routing In Flask – Coding Ninjas (www.codingninjas.com)
- Essential Guide to Understanding Routing – LearnVern (www.learnvern.com)
- Advanced patterns for views and routing – Explore Flask (exploreflask.com)
- Multiple routing in flask- Python – Stack Overflow (stackoverflow.com)
- Routing in Flask and Python (super simple!) – YouTube (www.youtube.com)
- Flask â Routing – TutorialsPoint (www.tutorialspoint.com)
- Everything you need to know about Flask for beginners. (www.mygreatlearning.com)
- Flask Framework: Deep Dive Into Routing – Chaitanya Srivastav (chaitanya-srivastav.medium.com)
- An Introduction to Python Flask Framework for Beginners (www.analyticsvidhya.com)
- Easy Ways to Build Flask Routes in Python – turing.com (www.turing.com)
- An Overview Of Flask Main Concepts And How It Works (simpleit.rocks)
- What is Flask in Python? – Code Institute Global (codeinstitute.net)
- Python Flask App Routing – DEV Community (dev.to)
- What is an ‘endpoint’ in Flask? – Make Me Engineer (makemeengr.com)
- Flask App Routing – TAE – Tutorial And Example (www.tutorialandexample.com)