我是Tornado的新手并编写基本应用程序但还需要添加错误处理。以下是代码。
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado import gen
from tornado.web import asynchronous
from tornado.options import define, options
define("port", default=8888, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", HomeHandler),
(r"/mycompany", myCustomHandler),
(r"/mycompany/", myCustomHandler),
]
super(Application, self).__init__(handlers)
class HomeHandler(tornado.web.RequestHandler):
def get(self):
self.render("home.html")
class myCustom(tornado.web.RequestHandler):
def get(self):
self.write("Processing....")
self.clear()
self.finish()
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()
home.html运行正常。
接下来,我希望用户使用http://host:port/mycompany/?id=9999等格式传递参数。
但是当有人进入* host:port / blahblah或* host:port / mycompany /?something = 9999时,想要显示404 PAGE。我该怎么做呢? 感谢。
答案 0 :(得分:1)
要对未知网址使用自定义错误页面,请使用default_handler_class
参数Application()
。 处理程序中引发的错误使用write_error
方法生成错误页面。对两者使用相同的错误处理有点复杂;这是基本的脚手架:
class BaseHandler(tornado.web.RequestHandler):
def write_error(self, status_code, **kwargs):
if status_code == 404:
self.render("404.html")
else:
self.render("error.html")
class My404Handler(BaseHandler):
def prepare(self):
raise tornado.web.HTTPError(404)
class MyCustomHandler(BaseHandler):
def get(self):
if not self.valid_arguments():
raise tornado.web.HTTPError(400)
app = Application([...], default_handler_class=My404Handler)