Home >Backend Development >Python Tutorial >How to Retrieve Variables from URLs in Flask Routes?

How to Retrieve Variables from URLs in Flask Routes?

Linda Hamilton
Linda HamiltonOriginal
2024-11-08 16:34:02752browse

How to Retrieve Variables from URLs in Flask Routes?

Retrieving Variables from URLs in Flask Routes

To obtain a unique ID from a URL that follows the pattern "landingpage-", Flask provides a straightforward method. The following responses provide detailed guidance:

Method 1: Variable URLs

Define a variable URL by inserting placeholders within the URL path and accepting the corresponding arguments in the view function.

@app.route('/landingpage<id>')  # /landingpageA
def landing_page(id):
    ...

Method 2: Path Variables with Slash

Use a slash separator to specify the variable portion of the URL:

@app.route('/landingpage/<id>')  # /landingpage/A
def landing_page(id):
    ...

URL Generation with url_for

Generate URLs using the url_for function:

url_for('landing_page',>

Query String Approach (Alternative)

Alternatively, you can pass the ID as part of the query string and retrieve it from the request object:

from flask import request

@app.route('/landingpage')
def landing_page():
    id = request.args['id']
    ...

Note that this approach is suitable when the ID is not mandatory. For required IDs, it's better to use variable URLs.

The above is the detailed content of How to Retrieve Variables from URLs in Flask Routes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn