Blake G
Blake G

Reputation: 581

Routing for multiple variable in a request string

I am having difficulty understanding how to grab variables from a request string in flask. I'm pretty sure this syntax is wrong, but can someone help me understand how to grab multiple variables from the request string?

@restServer.route('/end_point/<foo>&<bar>')
def like_provider(self,foo,bar):

Which syntax should I use when sending data?

http://url/foo&bar

OR

http://url/var=foo&var2=bar

In the second case, how would I write the routing code in Flask?

Upvotes: 2

Views: 199

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

There are two parts to a URL your view needs to care about: the URL path, and the query string. Both your examples are just path elements, really, the query string is everything after the ?.

It really depends on how your web application is supposed to be interacted with; a URL usually represents one resource, with the query string representing, well, a query on that resource.

Compare /users/102324 with /users?name=Joe+Soap; the former represents one user (with the id 102323, the latter URL is for all users, but includes a search for users matching a given name.

The path is the part you match with the route config; it matches your pattern exactly; for your two examples, the foo and bar placeholders capture everything (except for the / character); so both your URLs would work, and simply result in different values for foo and bar:

http://url/end_point/foo&bar  -> {'foo': 'foo', 'bar': 'bar'}
http://url/end_point/var=foo&var2=bar  -> {'foo': 'var=foo', 'bar': 'var2=bar'}

But you'd normally not use & in a URL path.

The query string, on the other hand is parsed for key-value pairs and can be accessed with the request.query object:

@route('/end_point')
def like_provider(self):
    foo = request.args.get('foo')
    bar = request.args.get('bar')

Upvotes: 6

Related Questions