前段时间重新拾了下tornado提供http服务,并简单整合了下框架,详情见 Github/quicktouch/tornado-quick

http 错误的统一抛出处理、以及设置默认的相应头

class BaseRequestHandler(tornado.web.RequestHandler):

    def data_received(self, chunk: bytes) -> Optional[Awaitable[None]]:
        pass

    # 设置统一的http响应头 https://stackoverflow.com/questions/42434645/set-headers-for-all-requests-in-tornado
    def set_default_headers(self):
        self.set_header("Content-Type", "application/json;charset=UTF-8")
c
    # 设置统一的错误返回
    def write_error(self, status_code, **kwargs):
        error_trace_list = traceback.format_exception(*kwargs.get("exc_info"))
        if DEBUG:
            reason = ""
            if len(error_trace_list) > 0:
                reason = error_trace_list[-1]
            http_error_with_reason(self, status_code, reason)
        else:
            http_error_response(self, status_code)


class NotFoundHandler(BaseRequestHandler):
    
    def data_received(self, chunk: bytes) -> Optional[Awaitable[None]]:
        pass

    def prepare(self):  # for all methods
        raise tornado.web.HTTPError(
            status_code=404,
            reason="Invalid resource path."
        )