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

使用python3.5中的aiohttp查询get URL的参数,python,Python,上面的代码是在Python3.6中运行的。我需要从示例URLhttp://localhost.com/sample?name=xyz&age=xy。我尝试了req.rel\u url.query和request.query\u string。它只给出了第一个参数值xyz,但我没有得到xy(年龄),这是查询中的第二个参数 如何获取这两个查询值?这里几乎没有错误 结果未在函数中定义。正确获取参数,但由于未定义result,因此会发生错误 您的目标是localhost.com,不确定这在您的计算机上是

上面的代码是在Python3.6中运行的。我需要从示例URL
http://localhost.com/sample?name=xyz&age=xy
。我尝试了
req.rel\u url.query
request.query\u string
。它只给出了第一个参数值xyz,但我没有得到xy(年龄),这是查询中的第二个参数


如何获取这两个查询值?

这里几乎没有错误

  • 结果
    未在函数中定义。正确获取参数,但由于未定义
    result
    ,因此会发生错误
  • 您的目标是
    localhost.com
    ,不确定这在您的计算机上是如何设置的,但它不应该工作
  • 下面是一个工作示例:

    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)
    
    然后您可以尝试:并且它正在工作。

    快速示例:

    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)
    

    我试着用上面的片段。我得到了一个KeyError错误:“找不到密钥:'年龄'”。结果的业务逻辑我还没有添加。但我面临的问题是,我无法读取第二个参数值(在本例中是age)本地主机已更改为我的计算机IP地址
    返回web。响应(text=str(result))
    str函数不是必需的,因为format方法已返回字符串。下面是对我的代码段的一些更改。1。localhost已更改为我的计算机IP,因此在查询http://:3000/sample?name=xyz&age=xy 2中。未在代码段中添加结果的业务逻辑。因为我在request.rel_url.query['age']中失败了。
    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}")