Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get query string parameters from url in aiohttp?

I tried to get query string parameters from url by using aiohttp, but this code does not work :

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)

I searched in the internet and everywhere it was written that you should use request.rel_url.query to get all parameters from query string, but I get error when running the code!!!!!

like image 946
Ali Najafi Avatar asked Jan 02 '23 08:01

Ali Najafi


1 Answers

You must not add query string to route specification, because aiohttp throws away query string when does route matching. request.rel_url.query works good, here is an example:

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)

Testing it:

$ curl 'localhost:8080/?call_id=100&status=200'
call_id = 100
status = 200
like image 153
Andrii Maletskyi Avatar answered Jan 05 '23 17:01

Andrii Maletskyi