我正在尝试更改 Tornado Web 应用程序实例在无法路由(或确认 Content-Type json)时给出的 native 404 响应。
我找不到执行此操作的文档,所以现在只是添加一个匹配所有内容的最终正则表达式:
import tornado.web
class BaseHandler(tornado.web.RequestHandler):
def write_error(self, status_code, **kwargs):
self.finish({
'error': {
'code': status_code,
'message': self._reason,
}
})
class NotFoundHandler(BaseHandler):
def get(self, *args, **kwargs):
raise tornado.web.HTTPError(
status_code=404,
reason="Invalid resource path."
)
app = tornado.web.Application([
(r"/ping", PingHandler),
# ...
(r"(.*)", NotFoundHandler),
])
这感觉有点像黑客。有没有办法更全局地设置它?
最佳答案
根据documentation您可以使用 default_handler_class
来执行此操作。
For 404 errors, use the
default_handler_class
Application setting. This handler should overrideprepare
instead of a more specific method likeget()
so it works with any HTTP method. It should produce its error page as described above: either by raising aHTTPError(404)
and overridingwrite_error
, or callingself.set_status(404)
and producing the response directly inprepare()
.
例如:
class NotFoundHandler(RequestHandler):
def prepare(self): # for all methods
raise tornado.web.HTTPError(
status_code=404,
reason="Invalid resource path."
)
app = Application(..., default_handler_class=NotFoundHandler)
关于python - Tornado Web 自定义 404,其中路径不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43793881/