Ben J.
Ben J.

Reputation: 806

Get a variable from the URL in a Flask route

I have a number of URLs that start with landingpage and end with a unique id. I need to be able to get the id from the URL, so that I can pass some data from another system to my Flask app. How can I get this value?

http://localhost/landingpageA
http://localhost/landingpageB
http://localhost/landingpageC

Upvotes: 42

Views: 121844

Answers (2)

perymerdeka
perymerdeka

Reputation: 823

like this the example

@app.route('/profile/<username>')
def lihat_profile(username):
    return "welcome to profile page %s" % username

Upvotes: 8

davidism
davidism

Reputation: 127390

This is answered in the quickstart of the docs.

You want a variable URL, which you create by adding <name> placeholders in the URL and accepting corresponding name arguments in the view function.

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

More typically the parts of a URL are separated with /.

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

Use url_for to generate the URLs to the pages.

url_for('landing_page', id='A')
# /landingpage/A

You could also pass the value as part of the query string, and get it from the request, although if it's always required it's better to use the variable like above.

from flask import request

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

# /landingpage?id=A

Upvotes: 100

Related Questions