Flask route with URI encoded component


Question

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!

1
19
11/15/2015 11:57:40 AM

Accepted Answer

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.

26
8/19/2011 3:33:06 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon