Search code examples
python-3.6aiohttp

Detailed class based view in aiohttp


I'm trying to make a class based view in aiohttp. I'm following the doc. All goes good but I can't find a way to make detailed views.

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)

This code will produce two endpoints:

POST /view
GET /view

But how to add the GET /view/:pk: using the class-based views? I know that I can make it manually, adding to the router without the class-based views but I'm looking for a way to use it here.

UPD: The goal is to generate the URLs like

"""
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)

Or at least get the URLs like:

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

Solution

  • For creating the additional behavior on class-based view add route decorator to View.

    
    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')