如何从aiohttp中的url获取查询字符串参数?

how to get query string parameters from url in aiohttp?

我尝试使用 aiohttp 从 url 获取查询字符串参数,但这段代码不起作用:

async def call_answer(request):
    print("request", request)
    params = request.rel_url.query
    print("parameters +++++", params["call_id"])
    conn = psycopg2.connect(connect_str)
    cursor = conn.cursor()
    sql = """
          update calls
          set status = %s
          where id = %s;
          """ % (params["status"], params["call_id"])
    cursor.execute(sql)
    conn.commit()

    return web.Response(
        content_type='application/json',
        text=json.dumps({
            'status': 'success'
        }))



if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='WebRTC audio / video / data-channels demo')
    parser.add_argument('--port', type=int, default=8080,
                        help='Port for HTTP server (default: 8080)')
    parser.add_argument('--verbose', '-v', action='count')
    args = parser.parse_args()

    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)

    app = web.Application()
    app.router.add_get('/{call_id}&{status}', call_answer)

我在互联网上搜索,到处都写着你应该使用 request.rel_url.query 从查询字符串中获取所有参数,但是当 运行 代码时我得到了错误!!!!!!

您不能在路由规范中添加查询字符串,因为aiohttp 在进行路由匹配时会丢弃查询字符串。 request.rel_url.query 效果很好,这里是一个例子:

from aiohttp import web


async def call_answer(request):
    params = request.rel_url.query
    return web.Response(text='\n'.join([
        'call_id = ' + params['call_id'],
        'status = ' + params['status'],
    ]))


app = web.Application()
app.router.add_get('/', call_answer)
web.run_app(app)

正在测试:

$ curl 'localhost:8080/?call_id=100&status=200'
call_id = 100
status = 200