2

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?

1 Answer 1

6

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')
Sign up to request clarification or add additional context in comments.

2 Comments

So to process /users?name=Joe+Soap&age=21 I would access the variables by name = request.args.get('name') and age = request.args.get('age')?
@b.j.g: exactly. You can specify that age should be a Python int: age = request.args.get('age', type=int) and it'll be converted if possible, or return None if not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.