tornado捕获和处理404错误的方法

yipeiwu_com5年前Python基础

Tornado 文档中提到但是这样只能捕获到handlers中列出的路径请求中的错误。

如果只定义了(r"/hello", HelloHandler) 一条规则,那么只能捕获到 /hello/other,这样的未定义路径请求,而像/he、/helloworld、/he/other这样的会直接显示Tornado默认的404错误页面,而不会显示自定义的错误页面。

解决方法很简单只需要在路由规则的最后加一条(r".*", BaseHandler),用于捕获未被其他规则捕获的所有请求,然后覆写get方法,并在方法中调用自定义的write_error方法。 例:

复制代码 代码如下:

class BaseHandler(tornado.web.RequestHandler):
    def get(self):
        self.write_error(404)

    def write_error(self, status_code, **kwargs):
        if status_code == 404:
            self.render('public/404.html')
        elif status_code == 500:
            self.render('public/500.html')
        else:
            self.write('error:' + str(status_code))

相关文章

python 获取指定文件夹下所有文件名称并写入列表的实例

如下所示: import os import os.path rootdir = "./pic_data" file_object = open('train_list.txt','...

解决pandas read_csv 读取中文列标题文件报错的问题

从windows操作系统本地读取csv文件报错 data = pd.read_csv(path) Traceback (most recent call last): Fi...

Python版名片管理系统

Python版名片管理系统

本文实例为大家分享了Python版名片管理系统的具体代码,供大家参考,具体内容如下 先建立cards_main的文件 import cards_tools #无限循环,由用户主动决...

python防止随意修改类属性的实现方法

如果不想允许随意修改一个类的某个属性,常用的方法是使用property装饰器以及在属性前加下划线。 class V: def __init__(self, x): se...

Python编写检测数据库SA用户的方法

本文讲述一个用Python写的小程序,用于有注入点的链接,以检测当前数据库用户是否为sa,详细代码如下: # Code by zhaoxiaobu Email: little.bu@...