aiohttp 中基于 class 的详细视图

Detailed class based view in aiohttp

我正在尝试在 aiohttp 中创建一个基于 class 的视图。我正在关注 doc。一切顺利,但我找不到制作详细视图的方法。

from aiohttp import web


class MyView(web.View):

    async def get(self):
        resp = await get_response(self.request)
        return resp

    async def post(self):
        resp = await post_response(self.request)
        return resp

    app.router.add_view('/view', MyView)

此代码将产生两个端点:

POST /view
GET /view

但是如何使用基于 class 的视图添加 GET /view/:pk:?我知道我可以手动制作它,在没有基于 class 的视图的情况下添加到路由器,但我正在寻找一种在这里使用它的方法。

更新: 目标是生成像

这样的 URL
"""
POST /view      # creation
GET /view       # a full list
GET /view/:id:  # detailed view

"""



from aiohttp import web


class MyView(web.View):

    async def get(self):
        resp = await get_response(self.request)
        return resp

    async def post(self):
        resp = await post_response(self.request)
        return resp

    async def detailed_get(self):
        resp = await post_response(self.request)
        return resp


    app.router.add_view('/view', MyView)

或者至少获取如下网址:

POST /view     # creation
GET /view/:id: # detailed view

要在基于 class 的视图上创建附加行为,请将路由装饰器添加到视图。


from aiohttp import web

routes = web.RouteTableDef()


@routes.view('/ert/{name}')
@routes.view('/ert/')
class MyView(web.View):

    async def get(self):
        return web.Response(text='Get method')

    async def post(self):
        return web.Response(text='Post method')