tornado 的错误页面 和 常用方法的调用顺序

tornado 的错误页面

from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.options import define, parse_config_file, options
from tornado.web import Application, RequestHandler

define('port', type=int, default=8888, multiple=False)
parse_config_file('config')

class ErrPageHandler(RequestHandler):
    def get(self, *args, **kwargs):
        self.write('err page')
        # 执行send_error方法时会触发tornado中write_error方法,该方法会根据错误代码返回相应的内容返回客户端
        self.send_error(404)  # 404: Not Found
        # self.send_error(401)  # 401: Unauthorized
        # self.send_error(200)  # 200: OK
        # self.send_error()  # 默认500: Internal Server Error

 	def write_error(self, status_code, **kwargs):
        if status_code == 404:
            self.write('

你访问的页面不存在!!!!

'
) else super().write_error(status_code, **kwargs) # 调用父类的write_error方法 def post(self, *args, **kwargs): pass url_list = [('/err', ErrPageHandler)] app = Application(url_list) server = HTTPServer(app) server.listen(options.port) IOLoop.current().start()
  • 说明
    • 在get方法中调用send_error方法时,会触发write_error方法,并根据相应的内容返回给客户端
    • send_error方法中参数的状态码必须为html定义中已有的状态码
class ErrPageHandler(RequestHandler):
    def get(self, *args, **kwargs):
        self.send_error(404)  # 404: Not Found
        # self.send_error(401)  # 401: Unauthorized
        # self.send_error(200)  # 200: OK
        # self.send_error()  # 默认500: Internal Server Error

    def write_error(self, status_code, **kwargs):
        if status_code == 404:
            self.write('

你访问的页面不存在!!!!

'
) else super().write_error(status_code, **kwargs) # 调用父类的write_error方法

tornado 中常用方法的调用顺序

方法名称 优先级 备注
set_default_headers 1 在get或post方法中调send_error方法时,会再次调用该方法
initialize 2
get / post 3
write_error 4
on_finish 5
finish 6

你可能感兴趣的:(tornado)