Search code examples
pythonpython-3.xpython-asyncioaiohttp

aiohttp: how to add sub_app to sub_app?


I need to add sub_app to sub_app. Here is my code

app = web.Application()

subapp = web.Application()
subapp.router.add_get('/page1/', handler)
app.add_subapp('/wt/', subapp)

subsubapp = web.Application()
subsubapp.router.add_get('/page2/', handler)
subapp.add_subapp('/sub/', subsubapp)

Why the page /wt/sub/page2/ is not found? I think that the path for subsubapp is a concatenation of /wt/ (sub_app) and /sub/ (subsubapp). Am I wrong? What is the rule?

Regards, Valery.


Solution

  • aiohttp version 2.3 has a subtle bug: it doesn't inform about improper sub application initialization order.

    Sub-application logically is frozen after registering in parent, adding new routes to it is an error.

    Not released yet aiohttp 3.0 raises explicit exception on app.add_subapp() call, see corresponding issue and pull request for more details.

    To fix your snippet reorder route registering calls:

    from aiohttp import web
    
    async def handler(request):
        return web.Response(text="OK")
    
    subsubapp = web.Application()
    subsubapp.router.add_get('/page2/', handler)
    
    subapp = web.Application()
    subapp.router.add_get('/page1/', handler)
    subapp.add_subapp('/sub/', subsubapp)
    
    app = web.Application()
    app.add_subapp('/wt/', subapp)
    
    web.run_app(app, host='127.0.0.1', port=8080)
    

    After this fetching http://127.0.0.1:8080/wt/sub/page2/ resources returns 200 OK.