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

S-K*_*-K' 30 python tornado

我目前正在使用以下内容来引发HTTP错误请求:

raise tornado.web.HTTPError(400)
Run Code Online (Sandbox Code Playgroud)

返回一个html输出:

<html><title>400: Bad Request</title><body>400: Bad Request</body></html>
Run Code Online (Sandbox Code Playgroud)

是否可以使用自定义正文返回HTTP响应代码?

Vis*_*ioN 38

你可以模拟RequestHandler.send_error方法:

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


Rod*_*yde 25

Tornado会调用RequestHandler.write_error输出错误,因此根据Tornado 文档的建议,VisioN方法的替代方法将覆盖它.这种方法的优点是它可以让你像以前一样加注.HTTPError

来源RequestHandler.write_error在这里.下面你可以看到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,
                })
Run Code Online (Sandbox Code Playgroud)


pun*_*lly 6

最好使用标准界面并在上面定义自定义消息HTTPError.

raise tornado.web.HTTPError(status_code=code, log_message=custom_msg)
Run Code Online (Sandbox Code Playgroud)

然后,您可以解析您的错误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>")
Run Code Online (Sandbox Code Playgroud)


Som*_*esh 5

def write_error(self, status_code, **kwargs):
    #Function to display custom error page defined in the handler.
    #Over written from base handler.
    data = {}
    data['code'] = status_code
    data['message'] = httplib.responses[status_code]
    # your other conditions here to create data dict
    self.write(TEMPLATES.load('error.html').generate(data=data))
Run Code Online (Sandbox Code Playgroud)

当过self.send_error()调用开始write_error()函数由请求处理程序调用.因此,您可以在此处创建自定义错误数据dict,并将其呈现给您的自定义错误页面.

http.responses [status_code]根据状态代码返回错误代码文本,如"找不到页面".