Tornado – Request Handlers

In tornado,

  • tornado.web.RequestHandler maps URLs to subclasses and
  • tornado.web.Application class starts a server at the beginning with certain settings

For instance, in the example below:

  • When a HTTP GET request is made to http://127.0.0.1:8888/, class Hello handles it & requests made to http://127.0.0.1:8888/user are catered by class User
  • A web formĀ  is rendered to the user when the client browses (Http Get) to /user
  • When the client fills in the form and clicks on ‘Submit Query’, a HTTP POST request is generated on /user URL
  • This request is then served by the post() method of handler class ‘User’ and the message with username and designation is rendered on the browser

Code


import tornado.ioloop
import tornado.web
class Hello(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
class User(tornado.web.RequestHandler):
def get(self):
form = """<form method="post">
<input type="text" name="username"/>
<input type="text" name="designation"/>
<input type="submit"/>
</form>"""
self.write(form)
def post(self):
username = self.get_argument('username')
designation = self.get_argument('designation')
self.write("Wow " + username + " you're a " + designation)
application = tornado.web.Application([
(r"/", Hello),
(r"/user/", User),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()

Form presented to the client

 

 

Response from web server

One thought on “Tornado – Request Handlers

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.