Ben
Ben

Reputation: 59

How to handle special characters in URL with Flask

I am using Flask to develop a mini API backend, I have following URL:

@app.route('/v1.0/post/check/<path:url>')
def check(url):
    print url
    //do some works

A sample API call looks like: /v1.0/post/check/http://exampleside.com/enter1/index.php?app=forum&act=threadview&tid=14066185

What I expected is to get and print URL string 'http://exampleside.com/enter1/index.php?app=forum&act=threadview&tid=14066185' in the code, but in fact, what I really get is only 'http://exampleside.com/enter1/index.php'

Seems Flask considers '?' and '&' as special chars and then split a URL automatically. So what I should do in order to get the URL as a whole in Flask?

Upvotes: 3

Views: 3817

Answers (2)

Robert Moskal
Robert Moskal

Reputation: 22553

You are trying to pass a url, including request parameters on a url.

You have two choices.

The smart one is to urlencode that part of the URL when you construct it. That will safely encode the ? and & symbols.

Here is an example so you can tell whether it's so. This:

Foo?g=one&two=2

will look like this:

Foo%3Fg%3Done%26two%3D2

That will be the last segment of the uri for your api.

The second one is to reconstruct the value from all the arguments flask splits up. But that strikes me as a lot of work.

Upvotes: 5

Chris Chambers
Chris Chambers

Reputation: 1365

This is because the ? and & indicate that you are receiving parameters in the URL.

To get them, you need to use the request object like so: app = request.args.get('app')

If you just want the whole url, parameters and all, try Robert's method.

Upvotes: 0

Related Questions