Reputation: 477
I'm new to Tornado and writing a basic application but also need to add Error handling. Below is the code.
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()
The home.html works fine.
Next, I would like users to pass parameters using format something like http://host:port/mycompany/?id=9999.
But want to display a 404 PAGE when somebody enters *host:port/blahblah or *host:port/mycompany/?something=9999. How do I go about doing that? Thanks.
Upvotes: 1
Views: 2328
Reputation: 22134
To use a custom error page for unknown URLs, use the default_handler_class
argument to Application()
. Errors raised within a handler use the write_error
method to produce error pages. Using the same error handling for both is a little complicated; here's the 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)
Upvotes: 1