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

时间:2018-05-26 05:21:51

标签: python string python-3.x aiohttp request.querystring

我尝试使用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从查询字符串中获取所有参数,但是在运行代码时出错!!!!!

1 个答案:

答案 0 :(得分:1)

您不能将查询字符串添加到路由规范中,因为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