Search code examples
aiohttp

How to add Run Nested applications in AioHttp


I am trying out nested application in AIOhttp but can't get it to run.

If I want my url to be like localhost/greet/ and localhost/greet/abc, I am using the following code but giving me 404 Not Found so my routing is not correct.

I am not able to find much online resources here as well.

Below is my code:

app = web.Application()
greet = web.Application()

app.router.add_get('/', index)
greet.router.add_get('/{name}', handle_name, name='name')

app.add_subapp('/greet/', greet)

web.run_app(app, host='127.0.0.1', port=8080)

async def handle_name(request):
    name = request.match_info.get('name', "Anonymous")
    txt = "Hello {}".format(name)
    return web.Response(text=txt)

Any guidance will be helpful!


Solution

  • Not entirely clear what your problem was, but this works fine:

    from aiohttp import web
    
    async def index_view(request):
        return web.Response(text='index\n')
    
    async def subapp_view(request):
        name = request.match_info.get('name', "Anonymous")
        txt = "Hello {}\n".format(name)
        return web.Response(text=txt)
    
    app = web.Application()
    app.router.add_get('/', index_view)
    
    greet = web.Application()
    greet.router.add_get('/{name}', subapp_view)
    
    app.add_subapp('/greet/', greet)
    
    if __name__ == '__main__':
        web.run_app(app, host='127.0.0.1', port=8080)
    

    and then testing with curl:

    ~ 0  25ms ➤  curl localhost:8080/
    index
    ~ 0  33ms ➤  curl localhost:8080/greet/world
    Hello world
    

    Hope that answers your question.