分裂路线.py通过aiohttp中的应用程序

2024-04-26 01:11:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我的项目结构如下:

apps
    app1
        __init__.py
        views.py
    app2
        __init__.py
        views.py
    __init__.py
    main.py
    routes.py

如何按应用程序划分路由,将它们放入自己的应用程序中,并像django的include do一样将它们包含在“全局”路由器中?你知道吗


Tags: apps项目djangopy应用程序路由includeinit
1条回答
网友
1楼 · 发布于 2024-04-26 01:11:20

你可以这样做:

在应用程序\app1中\视图.py

from aiohttp import web

async def route_path_def(request):
    return web.Response(body=b'Some response')

routes = (
    {'GET', '/route_path', route_path_def, 'route_path_name'}
)

在应用程序\app2中\视图.py

from aiohttp import web

async def another_route_path_def(request):
    return web.Response(body=b'Some response')

routes = (
    {'GET', '/another_route_path', another_route_path_def, 'another_route_path_name'}
)

英寸路线.py

从app1.views将路由作为app1\u路由导入 从app2.views将路由作为app2\u路由导入

routes = list()
routes.append(app1_routes)
routes.extend(app2_routes)

英寸主.py

from .routes import routes
from aiohttp import web

app = web.Application()

for method, path, func_name, page_name in routes:
    app.router.add_route(method, path, func_name, name=page_name)
web.run_app(app, port=5000)

为我工作很好:)

相关问题 更多 >