aiohttp中基于类的视图

vwv*_*dya 7 python aiohttp python-3.5

在aiohttp库中使用基于类的处理程序而不是函数的正确方法是什么?我习惯在Django中将处理程序编写为类,所以我想知道如何在aiohttp中正确地执行它?

And*_*lov 6

我假设您希望使用基于类的处理程序,以便为重用代码应用继承.

从技术上讲,aiohttp web-handler是接受请求参数并返回响应实例的任何协同程序.

例如

class BaseView:
    def __init__(self, ...):
        ...

    @asyncio.coroutine
    def __call__(self, request):
        return web.Response()

app.router.add_route('GET', '/', BaseView(...))
Run Code Online (Sandbox Code Playgroud)

可以用作制作Web处理程序层次结构的基类.

甚至

class Handler:
    def __init__(self, db):
        self._db = db

    @asyncio.coroutine
    def get_from_db(self, data):
        ...

    @asyncio.coroutine
    def handle_a(self, request):
        data = yield from self.get_from_db(
            self.extract_from_request_a(request))
        return web.Response(self.format_data(data))

    @asyncio.coroutine
    def handle_b(self, request):
        data = yield from self.get_from_db(
            self.extract_from_request_b(request))
        return web.Response(self.format_data(data))


handler = Handler(db)
app.router.add_route('GET', '/a', hadndler.handle_a)
app.router.add_route('GET', '/b', hadndler.handle_b)
Run Code Online (Sandbox Code Playgroud)

  • 仍然不知道如何添加post(request)函数.我应该实现as_view()方法在url中使用 (2认同)