Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python flask, how do you get the path parameters outside of the route function? [duplicate]

Tags:

python

flask

In flask, you can define path parameters like so:

@app.route('/data/<section>') def data(section):    print section 

In The above example, you can access the section variable only from the data endpoint (unless you pass it around in function parameter)

You can also get the query parameters by accessing the request object. this works from the endpoint function as well as any other called function, without needing to pass anything around

request.args['param_name'] 

my question is: is in possible to access the path parameter (like section above) in the same way as the query parameters?

like image 844
yigal Avatar asked Jan 05 '17 19:01

yigal


People also ask

How do you pass variables from one route to another in Flask?

The link to route /b in the template for /a could have query parameters added to it, which you could read in the route for /b . Alternatively you could store the value for a in a session variable to access it between views.

Can we have multiple URL paths pointing to the same route function?

In some cases you can reuse a Flask route function for multiple URLs. Or you want the same page/response available via multiple URLs. In that case you can add a second route to the function by stacking a second route decorator to the function. The code below shows how you use the a function for multiple URLs.

What is the default route request in Flask?

By default, a route only answers to GET requests. You can use the methods argument of the route() decorator to handle different HTTP methods. If GET is present, Flask automatically adds support for the HEAD method and handles HEAD requests according to the HTTP RFC.


1 Answers

It's possible to use request.view_args. The documentation defines it this way:

A dict of view arguments that matched the request.

Here's an example:

@app.route("/data/<section>") def data(section):     assert section == request.view_args['section'] 
like image 185
julienc Avatar answered Sep 22 '22 21:09

julienc