tornado 自定义错误处理方式

[source lang="python"]

import tornado.ioloop
import tornado.httpserver
import tornado.options
import tornado.web
import tornado.process

import json

from tornado.web import RequestHandler
from tornado.web import traceback

def write_error(self, status_code, **kwargs):
print "enter into write_error"

self.set_header("Content-Type", "application/json")

res = {"code": status_code, "value": "Server Internal Error"}

if status_code == 404:
res["value"] = "Not Found"

self.write(json.dumps(res))
self.finish()

setattr(RequestHandler, 'write_error', write_error)

class IndexHandle(tornado.web.RequestHandler):
def get(self):
self.write("Hello World")
return

if __name__ == "__main__":
tornado.options.parse_command_line()

# tornado.process.fork_processes(2)

__app__=tornado.web.Application(handlers=[(r'/', IndexHandle)], debug=True)
__http_server__=tornado.httpserver.HTTPServer(__app__)
__http_server__.listen(8002)
tornado.ioloop.IOLoop.instance().start()

[/source]

发表评论

电子邮件地址不会被公开。 必填项已用*标注