Random URL Content Fetcher with Tornado

  • Share this:

Code introduction


This code creates a simple Tornado web application that randomly fetches the content of a predefined URL and returns it.


Technology Stack : Tornado

Code Type : 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.wikipedia.org",
        "http://www.stackoverflow.com"
    ]
    return random.choice(urls)

def fetch_data():
    http_client = tornado.httpclient.HTTPClient()
    url = fetch_random_url()
    response = http_client.fetch(url)
    return response.body

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        data = fetch_data()
        self.write(data)

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

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()                
              
Tags: