首页 > 解决方案 > Aiohttp routing (aiohttp.web.RouteTableDef)

问题描述

I have a problems with RouteTableDef.
There is some project where routing structure like this:

1) There is file route.py.
routes.py

from aiohttp import web
routes = web.RouteTableDef()

2) There are some handlers in different files, for example: handler1.py

from aiohttp import web
from routes import routes

@routes.get('/get')
async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    return web.Response(text=text)

and so on.
3) and main file, where app runs:

from aiohttp import web
from routes import routes

if __name__ == '__main__':
    app = web.Application()
    app.router.add_routes(routes)

    web.run_app(app, host='localhost', port=8877)

The idea is:
all routes store at routes variable, when we wanna create new handler we import that variable from routes.py and use it.
In order to register routes to app, we import routes from routes.py.
And how to make it working with aiohttp v3.3.2?

The problem is: it works with aiohttp version 2.3.10.
But there is the real project with this way of routing and it works.
How to create a one place that will store routes?
I suppose that problem is in lib version, because that project doesn't work with the latest version of aiohttp.

标签: pythonaiohttp

解决方案


这里的问题是进口的顺序,正如已经回答的那样。这是我在每个文件中创建一个web.RouteTableDef()然后将它们放在一起的原因之一app.router

from .dashboard import routes as dashboard_routes
from .posts import routes as posts_routes

app.router.add_routes([
    *dashboard_routes,
    *posts_routes,
])

推荐阅读