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

阿里·纳加菲(Ali Najafi)

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

安德烈(Andrii Maletskyi)

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何直接从查询字符串(URL)获取Yii参数

如何从SEO友好的URL获取查询字符串参数?

从 JavaScript 中的 URL 获取查询字符串参数

获取URL查询字符串参数

如何从Next.js中的URL获取(查询字符串)参数?

如何获取Javascript或jQuery中的查询字符串参数?

如何在字符串url中替换查询参数

如何从URL字符串获取参数?

如何从URL中获取查询参数以及泛型而不是Spring Boot中GET请求的字符串

从URL获取动态查询字符串参数-AngularJS

NodeJS请求库如何获取完整的URL,包括URI和查询字符串参数

无法在 node express js 中获取 url 作为查询字符串参数

如何从URL查询参数中检查Rails参数哈希是否包含双引号字符串?

Koa Router:如何获取查询字符串参数?

React-如何从查询字符串获取参数值?

在Zend Framework 2.3中从查询字符串获取参数

从字符串查询中获取命名参数

无法在URL中访问Django查询字符串参数

如何在Java Play框架中获取查询字符串参数?

如何从CGI Perl脚本中的POST请求获取查询字符串参数?

如何在ASP.NET Core中获取查询字符串参数值?

如何从请求中获取所有查询字符串参数?

如何从Angular 5+中的对象创建带有查询参数的url字符串?

如何使用Rest Assured在GET URL中传递查询字符串参数?

如何在Azure API管理中为查询字符串参数指定重写URL

如何使用JavaScript从当前URL获取查询字符串?

如何获取带有“?”的URL查询字符串 里面?

Owin获取查询字符串参数

从日志文件中的URL获取查询字符串