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)
上面的代码在python 3.6中运行。我需要从示例URL中提取查询参数值(xyz&xy)http://localhost.com/sample?name=xyz&age=xy
。我试过了req.rel_url.query
,也尝试过了request.query_string
。它只给出第一个参数值xyz,但没有得到xy(年龄),后者是查询中的第二个参数。
如何获得两个查询值?
您在这里几乎没有错误。
result
未在您的函数中定义。您以正确的方式获取了参数,但是随后发生result
未定义的错误localhost.com
,不确定在您的计算机上如何设置,但是它不起作用。因此,这是工作示例:
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)
那么您可以尝试:http:// localhost:11111 / sample?name = xyz&age = xy并且它可以正常工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句