Simple Tornado Web Application with Main Handler

  • Share this:

Code introduction


This code example creates a simple Tornado Web application, including a main handler class and an application creation function. The main handler class responds to GET requests and returns a simple string. The application creation function configures the routes of the web application.


Technology Stack : Tornado

Code Type : Tornado Web Application

Code Difficulty : Intermediate


                
                    
import tornado.ioloop
import tornado.web
import tornado.httpclient
import random

def fetch_random_url():
    urls = [
        "http://www.example.com",
        "http://www.google.com",
        "http://www.github.com",
        "http://www.stackoverflow.com",
        "http://www.wikihow.com"
    ]
    http_client = tornado.httpclient.HTTPClient()
    url = random.choice(urls)
    response = http_client.fetch(url)
    return response.body

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])                
              
Tags: