pythonquery-stringaiohttp

How to make dynamic path that will be represented as list in aiohttp server?


Let's say that I have an example code:

from aiohttp import web

async def example(r):
    a = r.match_info.get('a')
    b = r.match_info.get('b')
    c = r.match_info.get('c')
    return web.Response(text=f'[{a}, {b}, {c}]')

app = web.Application()
app.add_routes([web.get('/args/{a}/{b}/{c}', example)])

web.run_app(app)

And now after accessing

http://localhost:8080/args/A/B/C

I'm getting

[A, B, C]

response. The question is what is a correct syntax for list (or tuple) like path?

In other words I want to access a URL with random number of arguments like

http://localhost:8080/args/r/a/n/d/o/m/1/2/3

and get a list or tuple of

('r', 'a', 'n', 'd', 'o', 'm', '1', '2', '3')

elements


Solution

  • You can use a regex to catch all requests that start with /args/:

    from aiohttp import web
    
    async def example(r):
        args = r.match_info.get('args').split("/")
        return web.Response(text=f"{type(args)}: {args}")
    
    app = web.Application()
    app.add_routes([web.get('/args/{args:.*}', example)])
    
    web.run_app(app)
    

    Then:

    http://localhost:8080/args/r/a/n/d/o/m/1/2/3
    
    <class 'list'>: ['r', 'a', 'n', 'd', 'o', 'm', '1', '2', '3']