python - 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.
解决方案
这里的问题是进口的顺序,正如已经回答的那样。这是我在每个文件中创建一个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,
])
推荐阅读
- laravel - 如何使用 Unisharp laravel 文件管理器管理公共和私人文件?
- r - 将框和轴限制在 plot.raster 中的范围内
- sql - 查询应返回 sysdate @ 特定时间的结果
- android - 带有 LENGTH_LONG 的 Snackbar 的实际持续时间是多少
- android - 将参数发布到 API 的最佳方式是什么?
- grails - 如何从控制器响应/发送多个对象以在 grails 中查看?
- ios - 如何在 Xamarin iOS App 中启用定位服务
- c++ - 如何使用感知器对插值数据进行归一化?
- azure-pipelines - 为什么拉取请求构建验证中的路径过滤器不能按预期工作?
- mysql - 如何处理 mysql 结果查询以通过大查询表发送它们