Skip to content

Adding routes to subapps is broken after attaching subapp to the parent app #2656

Closed
@webknjaz

Description

Long story short

If one adds routes to subapp before app.add_subapp accessing them works well, otherwise it results in 404.

Expected behaviour

It's naturally expected that routing will work well regardless of the order of function calls.

Actual behaviour

Given sub_app_cbv.py:

import sys
import aiohttp.web

API_URL_PREFIX = r'/api/v1'

class PingView(aiohttp.web.View):
    async def get(self):
        return aiohttp.web.Response(text='pong')

def just_app_with_routes_def(app, api_app):
    app.router.add_route('GET', API_URL_PREFIX + r'/ping/', PingView)

def sub_app_after_routes_def(app, api_app):
    api_app.router.add_route('GET', r'/ping/', PingView)
    app.add_subapp(API_URL_PREFIX, api_app)

def sub_app_before_routes_def(app, api_app):
    app.add_subapp(API_URL_PREFIX, api_app)
    api_app.router.add_route('GET', r'/ping/', PingView)

def run_app(coro_name):
    print(f'Going to run {coro_name}')
    setup_app = globals()[coro_name]
    app = aiohttp.web.Application()
    api_app = aiohttp.web.Application()
    setup_app(app, api_app)
    aiohttp.web.run_app(app)

def main():
    if len(sys.argv) < 2:
        raise RuntimeError('Supply one cli argument plz [just_app_with_routes_def|sub_app_after_routes_def|sub_app_before_routes_def]')
    coro_name = sys.argv[1]
    run_app(coro_name)

__name__ == '__main__' and main()
Demo 1
$ python sub_app_cbv.py just_app_with_routes_def
Going to run just_app_with_routes_def
======== Running on http://0.0.0.0:8080 ========
(Press CTRL+C to quit)
$ http :8080/api/v1/ping/
HTTP/1.1 200 OK
Content-Length: 4
Content-Type: text/plain; charset=utf-8
Date: Thu, 11 Jan 2018 23:17:52 GMT
Server: Python/3.6 aiohttp/2.3.7
pong
Demo 2
$ python sub_app_cbv.py sub_app_after_routes_def
Going to run sub_app_after_routes_def
======== Running on http://0.0.0.0:8080 ========
(Press CTRL+C to quit)
$ http :8080/api/v1/ping/
HTTP/1.1 200 OK
Content-Length: 4
Content-Type: text/plain; charset=utf-8
Date: Thu, 11 Jan 2018 23:20:58 GMT
Server: Python/3.6 aiohttp/2.3.7
pong
Demo 3
$ python sub_app_cbv.py sub_app_before_routes_def
Going to run sub_app_before_routes_def
======== Running on http://0.0.0.0:8080 ========
(Press CTRL+C to quit)
$ http :8080/api/v1/ping/
HTTP/1.1 404 Not Found
Content-Length: 14
Content-Type: text/plain; charset=utf-8
Date: Thu, 11 Jan 2018 23:21:41 GMT
Server: Python/3.6 aiohttp/2.3.7
404: Not Found

Steps to reproduce

See above.

Your environment

Gentoo laptop, pyenv, 3.6. Not really env-related.

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions