Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 696
gmrli Avatar asked Dec 11 '22 08:12

gmrli


2 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.

like image 94
PerunSS Avatar answered Mar 06 '23 03:03

PerunSS


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}")
like image 42
Slipstream Avatar answered Mar 06 '23 02:03

Slipstream