|
| 1 | +import abc |
| 2 | +import json |
| 3 | +import logging |
| 4 | +from typing import Optional, Awaitable |
| 5 | + |
| 6 | +from tornado import web |
| 7 | + |
| 8 | +from ...logger import LOG |
| 9 | + |
| 10 | +_RESP_BAD_REQUEST = {'code': '5101', 'message': ['Bad request: fail to parse body as JSON object!']} |
| 11 | + |
| 12 | + |
| 13 | +class APIHandler(web.RequestHandler): |
| 14 | + LOG = LOG |
| 15 | + |
| 16 | + def __init__(self, *args, **kwargs): |
| 17 | + super().__init__(*args, **kwargs) |
| 18 | + |
| 19 | + @abc.abstractmethod |
| 20 | + def response(self, *args, **kwargs) -> dict: |
| 21 | + raise NotImplementedError() |
| 22 | + |
| 23 | + def set_default_headers(self) -> None: |
| 24 | + self.set_header('Content-Type', 'application/json; charset=utf-8') |
| 25 | + |
| 26 | + def data_received(self, chunk: bytes) -> Optional[Awaitable[None]]: |
| 27 | + pass |
| 28 | + |
| 29 | + async def post(self, *args, **kwargs): |
| 30 | + try: |
| 31 | + req = self.request.body |
| 32 | + body = json.loads(req.decode('utf-8')) |
| 33 | + kwargs.update(body) |
| 34 | + except json.decoder.JSONDecodeError: # invalid request body, cannot be parsed as JSON |
| 35 | + return self.finish(_RESP_BAD_REQUEST) |
| 36 | + |
| 37 | + resp = dict(code=5200, message=['success']) |
| 38 | + try: |
| 39 | + result = self.response(*args, **kwargs) # this call may throw TypeError when argument missing |
| 40 | + resp['data'] = result |
| 41 | + except Exception as e: |
| 42 | + if LOG.level == logging.DEBUG: |
| 43 | + self.LOG.error(e, exc_info=True) |
| 44 | + return self.finish({'code': 5201, 'message': [str(e)]}) |
| 45 | + |
| 46 | + resp = json.dumps(resp, ensure_ascii=False, default=str, separators=(',', ':')) |
| 47 | + return self.finish(resp) |
0 commit comments