python - Error Handling in Tornado -
i'm new tornado , writing basic application need add error handling. below code.
import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web tornado import gen tornado.web import asynchronous tornado.options import define, options define("port", default=8888, help="run on 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()
the home.html works fine.
next, users pass parameters using format http://host:port/mycompany/?id=9999.
but want display 404 page when enters *host:port/blahblah or *host:port/mycompany/?something=9999. how go doing that? thanks.
to use custom error page unknown urls, use default_handler_class
argument application()
. errors raised within handler use write_error
method produce error pages. using same error handling both little complicated; here's basic scaffolding:
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)
Comments
Post a Comment