Query parameters of the get URL using aiohttp from python3.5

Question:

async def method(request):
    ## here how to get query parameters
    param1 = request.rel_url.query['name']
    param2 = request.rel_url.query['age']
    return web.Response(text=str(result))


if __name__ == '__main__':
    app = web.Application()
    app.router.add_route('GET', "/sample", method)    

    web.run_app(app,host='localhost', port=3000)

The above code is running in python 3.6. I need to extract the query parameter values (xyz & xy) from the sample URL http://localhost.com/sample?name=xyz&age=xy. I Tried with req.rel_url.query and also with request.query_string. It was giving only the first parameter value xyz, but I was not getting xy (age) which was the second parameter in the query.

How can I get both the query values?

Asked By: gmrli

||

Answers:

You have few errors here.

  1. result is not defined in your function. You get params right way, but then error occurs as result is not defined
  2. You’re targeting localhost.com, not sure how that is set on your machine, but it shouldn’t work.

So, here is working example:

from aiohttp import web

async def method(request):
    ## here how to get query parameters
    param1 = request.rel_url.query['name']
    param2 = request.rel_url.query['age']
    result = "name: {}, age: {}".format(param1, param2)
    return web.Response(text=str(result))


if __name__ == '__main__':
    app = web.Application()
    app.router.add_route('GET', "/sample", method)

    web.run_app(app,host='localhost', port=11111)

then you can try: http://localhost:11111/sample?name=xyz&age=xy and it is working.

Answered By: Aleksandar Varicak

Quick example:

async def get_handler(self, request):

    param1 = request.rel_url.query.get('name', '')
    param2 = request.rel_url.query.get('age', '')

    return web.Response(text=f"Name: {param1}, Age: {param2}")
Answered By: Slipstream

The topic is old but I have encountered a similar problem: turns out the issue didn’t come from the server but the client:

  • curl http://localhost.com/sample?name=xyz&age=xy was indeed sending only the first parameter.
  • However curl "http://localhost.com/sample?name=xyz&age=xy" gave the desired result.

Make sure the parameters are well sent with the request

Answered By: rust
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.