Class based views in aiohttp

What is the correct approach to using class-based handlers instead of functions in the aiohttp library? I'm used to writing handlers as classes in Django , so I'm wondering how to do this correctly in aiohttp ?

+7
source share
2 answers

I assume that you want to use class-based handlers to apply inheritance to reuse code.

Technically, the aiohttp web handler is any coroutine that accepts a request parameter and returns an instance of the response.

for instance

class BaseView: def __init__(self, ...): ... @asyncio.coroutine def __call__(self, request): return web.Response() app.router.add_route('GET', '/', BaseView(...)) 

can be used as a base class to create a hierarchy of web handlers.

Or even

 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) 
+6
source

You can use it like this:

 from aiohttp import web from datetime import datetime class TokenView(web.View): async def get(self): token = datetime.now().strftime("%Y%m%d%H%M%S") room = self.request.match_info.get("room", None) return web.json_response({"room": room, "token": token, "result": "OK"}) async def post(self): room = self.request.match_info.get("room", None) token = datetime.now().strftime("%Y%m%d%H%M%S") return web.json_response({"room": room, "token": token, "result": "OK"}) if __name__ == "__main__": app = web.Application() app.router.add_view("/token/{room}", TokenView) print(app.router.named_resources()) web.run_app(app) 
0
source

All Articles