如何在Tornado中返回没有默认模板的HTTP错误代码?

2024-04-18 08:47:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我当前正在使用以下命令引发HTTP错误请求:

raise tornado.web.HTTPError(400)

返回html输出:

<html><title>400: Bad Request</title><body>400: Bad Request</body></html>

是否可以只返回带有自定义主体的HTTP响应代码?


Tags: 代码命令webhttptitlerequesthtml错误
3条回答

您可以模拟^{}方法:

class MyHandler(tornado.web.RequestHandler):
    def get(self):
        self.clear()
        self.set_status(400)
        self.finish("<html><body>My custom body</body></html>")

最好使用标准接口并在HTTPError上定义自定义消息。

raise tornado.web.HTTPError(status_code=code, log_message=custom_msg)

然后,可以分析RequestHandler中的错误并检查消息:

class CustomHandler(tornado.web.RequestHandler):
    def write_error(self, status_code, **kwargs):
        err_cls, err, traceback = kwargs['exc_info']
        if err.log_message and err.log_message.startswith(custom_msg):
            self.write("<html><body><h1>Here be dragons</h1></body></html>")

Tornado调用^{}来输出错误,因此VisioN's approach的替代方法是根据Tornado的建议重写它。这种方法的优点是它将允许您像以前一样提高HTTPError

RequestHandler.write_error的源是here。下面您可以看到一个简单修改write_error的示例,如果您以kwargs格式提供原因,该修改将更改设置状态代码并更改输出。

def write_error(self, status_code, **kwargs):
    if self.settings.get("serve_traceback") and "exc_info" in kwargs:
        # in debug mode, try to send a traceback
        self.set_header('Content-Type', 'text/plain')
        for line in traceback.format_exception(*kwargs["exc_info"]):
            self.write(line)
        self.finish()
    else:
        self.set_status(status_code)
        if kwargs['reason']:
            self.finish(kwargs['reason'])
        else: 
            self.finish("<html><title>%(code)d: %(message)s</title>"
                "<body>%(code)d: %(message)s</body></html>" % {
                    "code": status_code,
                    "message": self._reason,
                })

相关问题 更多 >