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

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

最佳答案

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

关于python - 如何从aiohttp中的url获取查询字符串参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50539573/

相关文章:

python - 如何打印密码组合(但每个索引都有自定义约束)

python-3.x - Pygame:当位 block 传输到 SRCALPHA 表面时,文本失去抗锯齿功能

linux - 如何在 linux 中使用 cx_freeze 创建要在 windows 中使用的包

python - sqlalchemy - 如何复制深复制条目及其所有外部关系

python - 使用 nlp 从句子中挑选主语 + 形容词对

python - 检查字符串末尾是否包含子字符串

python - python中如何造成栈溢出和堆溢出

python - 更改 tensorflow 中张量的比例

python - GAE Python - 'Clamp' 日期一起形成 'tree' 结构

android - Kotlin:如何获取字符串中 "@"之后的字符?