2

How do I create a url in Flask that looks like:

localhost/something/info?userID=123&itemID=456

I am intressed in how to generate the info?userID=123&itemID=456 part.

Is it:

@app.route('something/info<userID>&<itemID>/')
do_something(userID, itemID):
    return

And I have seen something about "next" being used. But can't find any good example.

Edit

I looked at the other question but I didn't understand the example there.

Danila Ganchar
  • 10,266
  • 13
  • 49
  • 75
FluffPeg
  • 43
  • 6
  • Possible duplicate of [How to obtain values of parameters of get request in flask?](http://stackoverflow.com/questions/22383458/how-to-obtain-values-of-parameters-of-get-request-in-flask) – Kewin Dousse May 11 '17 at 11:12

1 Answers1

1

In your case userID and itemID are GET parameters but not part of route.

Flask request has view_args(which will used as arguments to view) and args(other parameters that will not be set to view function, but you can use them).

Here an example which can explain how it works.

@app.route('/<string:route_arg>/')
def route(route_arg):
    message = [
        # route_arg - part of route and argument of our view function
        'route_arg = %s ' % route_arg,
        # we can get route_arg from request
        'route_arg from request = %s ' % request.view_args.get('route_arg'),
        # request.args - parameters after '?' in url
        'userID = %s' % request.args.get('userID'),
        'itemID = %s' % request.args.get('itemID'),
        # example of url
        'url with args = %s' % url_for('route', route_arg='info', userID=123, itemID=456)
    ]
    return '<br/>'.join(message)

Let's open /info/ you will see the next result:

route_arg = info # because is part of route and argument
route_arg from request = info 
# because we didn't set parameters
userID = None 
itemID = None
url with args = /info/?itemID=456&userID=123

Let's open /info/?itemID=456&userID=123:

route_arg = info 
route_arg from request = info 
# not part of route, but part of request string(?itemID=456&userID=123)
userID = 123
itemID = 456
url with args = /info/?itemID=456&userID=123

So, in your case parameters will not used as arguments to view. You should work with them using request.args.

Danila Ganchar
  • 10,266
  • 13
  • 49
  • 75