Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask route with URI encoded component

Tags:

python

flask

It seems Flask doesn't support routes with a URI encoded component. I'm curious if I'm doing something wrong, or if there is a special flag I need to include.

My route looks something like this:

@app.route('/foo/<encoded>/bar/')
def foo(encoded):
  # ...
  pass

The URL that this should match can look like these:

http://foobar.com/foo/xxx/bar/ # matched correctly, no URI component
http://foobar.com/foo/x%2Fx%2Fx%2F/bar/ # not matched correctly, URI component

Former URL works, latter spits out a lovely 404.

Thanks!

like image 214
sholsapp Avatar asked Aug 17 '11 23:08

sholsapp


People also ask

How do you pass parameters in a URL in 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.

Does Flask automatically decode URL?

No, Flask is usually handling percent encoding exactly right. Parameters in a URL are percent encoded, and these are decoded for you when the WSGI environment is set up. Flask then passes this on to your route when matching. You do not need to decode the parameter value again, remove your urllib.

Which code block is used in Python Flask to map the URLs to a specific function that will handle the logic for that URL?

route("/") is a Python decorator that Flask provides to assign URLs in our app to functions easily.


1 Answers

Add path to your url rule:

@app.route('/foo/<path:encoded>/bar/')

Update per comment: The route API docs are here: http://flask.pocoo.org/docs/api/#flask.Flask.route. The underlying classes that implement the path style route converter are here: http://werkzeug.pocoo.org/docs/routing/#custom-converters (this is one of the really nice parts of pocoostan.) As far as the trailing slashes, there are special rules that amount to:

If a rule ends with a slash and is requested without a slash by the user, the user is automatically redirected to the same page with a trailing slash attached.

If a rule does not end with a trailing slash and the user request the page with a trailing slash, a 404 not found is raised.

Also keep in mind that if you are on Apache and are expecting a slash-trailed url, ie a bookmarklet that submits to http://ex.com/foo/<path:encoded>/bar and encoded gets something with double slashes, Apache will convert multiple slashes to a single one.

like image 148
unmounted Avatar answered Sep 29 '22 04:09

unmounted