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?
You have few errors here.
result
is not defined in your function. You get params right way, but then error occurs as result
is not definedlocalhost.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.
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}")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With