有趣的
validate_absolute_path
函数,如果不存在,为什么不重写它以提供默认文件?
import tornado
import tornado.web
import tornado.ioloop
import os
DEFAULT_ABSPATH = os.path.dirname(os.path.abspath(__file__))
class StaticFileOrDefaultHandler(tornado.web.StaticFileHandler):
def validate_absolute_path(self, root, absolute_path):
try:
return super(StaticFileOrDefaultHandler, self).validate_absolute_path(root, absolute_path)
except tornado.web.HTTPError as e:
if e.status_code == 404:
return os.path.join(DEFAULT_ABSPATH, 'default.png')
raise e
app = tornado.web.Application([
(r'/(.*)', StaticFileOrDefaultHandler, { 'path': DEFAULT_ABSPATH }),
])
if __name__ == '__main__':
app.listen(8888)
tornado.ioloop.IOLoop.instance().start()
编辑
HTTPError(403)
检查
status_code
如果引发的错误是
404
.