前段时间重新拾了下tornado提供http服务,并简单整合了下框架,详情见 Github/quicktouch/tornado-quick。
http 错误的统一抛出处理、以及设置默认的相应头
class BaseRequestHandler(tornado.web.RequestHandler):
def data_received(self, chunk: bytes) -> Optional[Awaitable[None]]:
pass
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):
raise tornado.web.HTTPError(
status_code=404,
reason="Invalid resource path."
)