Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture URL with query string as parameter in Flask route

Tags:

python

flask

Is there a way for Flask to accept a full URL as a URL parameter?

I am aware that <path:something> accepts paths with slashes. However I need to accept everything including a query string after ?, and path doesn't capture that.

http://example.com/someurl.com?andother?yetanother

I want to capture someurl.com?andother?yetanother. I don't know ahead of time what query args, if any, will be supplied. I'd like to avoid having to rebuild the query string from request.args.

like image 599
Jacek Perry Avatar asked Sep 28 '15 04:09

Jacek Perry


2 Answers

the path pattern will let you capture more complicated route patterns like URLs:

@app.route('/catch/<path:foo>')
def catch(foo):
    print(foo)
    return foo

The data past the ? indicate it's a query parameter, so they won't be included in that patter. You can either access that part form request.query_string or build it back up from the request.args as mentioned in the comments.

like image 116
Doobeh Avatar answered Sep 30 '22 05:09

Doobeh


Due to the way routing works, you will not be able to capture the query string as part of the path. Use <path:path> in the rule to capture arbitrary paths. Then access request.url to get the full URL that was accessed, including the query string. request.url always includes a ? even if there was no query string. It's valid, but you can strip that off if you don't want it.

@app.route("/<path:path>")
def index(path=None):
    return request.url.rstrip("?")

For example, accessing http://127.0.0.1:5000/hello?world would return http://127.0.0.1:5000/hello?world.

like image 43
davidism Avatar answered Sep 30 '22 04:09

davidism