使用python3.5中的aiohttp查询get URL的参数

2024-03-28 12:07:27 发布

您现在位置: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)

上面的代码是在Python3.6中运行的。我需要从示例URLhttp://localhost.com/sample?name=xyz&age=xy中提取查询参数值(xyz&xy)。我试过req.rel_url.query,也试过request.query_string。它只给出了第一个参数值xyz,但我没有得到xy(age),它是查询中的第二个参数。

如何获取这两个查询值?


Tags: samplenamewebapplocalhosturlageasync
1条回答
网友
1楼 · 发布于 2024-03-28 12:07:27

你这里很少出错。

  1. result未在函数中定义。您以正确的方式获取参数,但当未定义result时会发生错误
  2. 你的目标是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并且它正在工作。

相关问题 更多 >