|
| 1 | +import json |
| 2 | +import tracemalloc |
| 3 | +import typing |
| 4 | +from http import HTTPStatus |
| 5 | + |
| 6 | +from aiohttp.web import Application, Request, Response, View |
| 7 | +from aiohttp.web_middlewares import _Middleware as AIOHTTPMiddleware |
| 8 | + |
| 9 | +from events_protocol.core.views.base import BaseHealth, BaseView |
| 10 | +from events_protocol.core.utils.encoder import JSONEncoder |
| 11 | + |
| 12 | + |
| 13 | +async def init_app( |
| 14 | + routes: typing.List[typing.Tuple[View, str]], |
| 15 | + middlewares: typing.Iterable[AIOHTTPMiddleware] = [], |
| 16 | +) -> Application: |
| 17 | + |
| 18 | + tracemalloc.start() |
| 19 | + app = Application(middlewares=middlewares) |
| 20 | + for view, path in routes: |
| 21 | + app.router.add_view(path, view) |
| 22 | + |
| 23 | + return app |
| 24 | + |
| 25 | + |
| 26 | +_NOT_ALLOWED_AIOHTTP = Response(status=HTTPStatus.METHOD_NOT_ALLOWED) |
| 27 | + |
| 28 | + |
| 29 | +class AIOHTTPView(BaseView, View): |
| 30 | + request: Request |
| 31 | + body: str = None |
| 32 | + |
| 33 | + def __init__(self, *args, **kwargs): |
| 34 | + self.request = args[0] |
| 35 | + super().__init__(*args, **kwargs) |
| 36 | + |
| 37 | + def __iter__(self): |
| 38 | + return self._iter().__await__() |
| 39 | + |
| 40 | + async def get_body(self): |
| 41 | + if not self.body and self.request.body_exists: |
| 42 | + _body: bytes = await self.request.content.read(-1) |
| 43 | + self.body = _body.decode("utf-8") |
| 44 | + return self.body |
| 45 | + |
| 46 | + async def get(self, *args, **kwargs): |
| 47 | + return await self._get(*args, **kwargs) |
| 48 | + |
| 49 | + async def _get(self, *args, **kwargs): |
| 50 | + return _NOT_ALLOWED_AIOHTTP |
| 51 | + |
| 52 | + async def put(self, *args, **kwargs): |
| 53 | + await self.get_body() |
| 54 | + return await self._put(*args, **kwargs) |
| 55 | + |
| 56 | + async def _put(self, *args, **kwargs): |
| 57 | + return _NOT_ALLOWED_AIOHTTP |
| 58 | + |
| 59 | + async def post(self, *args, **kwargs): |
| 60 | + await self.get_body() |
| 61 | + return await self._post(*args, **kwargs) |
| 62 | + |
| 63 | + async def _post(self, *args, **kwargs): |
| 64 | + return _NOT_ALLOWED_AIOHTTP |
| 65 | + |
| 66 | + async def delete(self, *args, **kwargs): |
| 67 | + return await self._delete(*args, **kwargs) |
| 68 | + |
| 69 | + async def _delete(self, *args, **kwargs): |
| 70 | + return _NOT_ALLOWED_AIOHTTP |
| 71 | + |
| 72 | + def get_query_args(self): |
| 73 | + return self.request.rel_url.query or dict() |
| 74 | + |
| 75 | + async def write_response( |
| 76 | + self, http_status: HTTPStatus, response_body: dict, headers: dict = {}, |
| 77 | + ): |
| 78 | + headers.update(self._base_header) |
| 79 | + return Response( |
| 80 | + body=json.dumps(response_body, cls=JSONEncoder), status=http_status, headers=headers, |
| 81 | + ) |
| 82 | + |
| 83 | + |
| 84 | +class AIOHTTPHealthCheckView(BaseHealth, AIOHTTPView): |
| 85 | + pass |
0 commit comments