Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a variable from the URL in a Flask route

Tags:

python

url

flask

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 
like image 651
Ben J. Avatar asked Feb 03 '16 21:02

Ben J.


People also ask

How can I get the named parameters from a URL using Flask?

In the first one we would use request. args. get('<argument name>') where request is the instance of the class request imported from Flask. Args is the module under which the module GET is present which will enable the retrieve of the parameters.

How do you use URL variables?

To add a URL variable to each link, go to the Advanced tab of the link editor. In the URL Variables field, you will enter a variable and value pair like so: variable=value. For example, let's say we are creating links for each store and manager.

How do you pass multiple parameters in a Flask URL?

To add multiple parameters in a Python Flask app route, we can add the URL parameter placeholders into the route string. @app. route('/createcm/<summary>/<change>') def createcm(summary=None, change=None): #... to create the createcm view function by using the app.


1 Answers

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 
like image 77
davidism Avatar answered Sep 19 '22 16:09

davidism