Home > Article > Backend Development > How to Extract Variables from a URL in a Flask Route?
Get a Variable from the URL in a Flask Route
While working with web applications, it's essential to extract specific information from the URL to manipulate data or perform specific actions within the application. Flask, a web framework for Python, provides several approaches to obtain variables from URLs in a route.
Using Variable URLs
The most straightforward approach involves using variable URLs. Flask allows you to create dynamic URLs by including
@app.route('/landingpage<id>') def landing_page(id): ...
This route will match any URL that starts with '/landingpage' and has a unique identifier after it, such as '/landingpageA', '/landingpageB', and so on. You can then access the variable value as id within the landing_page function.
Using URL Segments
Another common practice is to use URL segments separated by '/'. This allows for more complex patterns and hierarchical structures:
@app.route('/landingpage/<id>') def landing_page(id): ...
In this example, the /landingpage/
Using url_for
Flask provides the url_for helper function to generate URLs for specific routes:
url_for('landing_page',>
Using Query Strings
While less preferable for required parameters, you can also capture values from the query string:
from flask import request @app.route('/landingpage') def landing_page(): id = request.args['id'] ...
In this case, the ID will be available as the id variable.
The above is the detailed content of How to Extract Variables from a URL in a Flask Route?. For more information, please follow other related articles on the PHP Chinese website!