You can download this code by clicking the button below.
This code is now available for download.
This function creates a simple Tornado web application that randomly accesses a predefined list of URLs and returns the results to the user.
Technology Stack : Tornado, HTTPClient
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.google.com",
"http://www.example.com",
"http://www.wikipedia.org",
"http://www.stackoverflow.com"
]
return random.choice(urls)
class MainHandler(tornado.web.RequestHandler):
def get(self):
url = fetch_random_url()
http_client = tornado.httpclient.AsyncHTTPClient()
http_client.fetch(url, self.handle_response)
def handle_response(self, response):
if response.error:
self.write("Error: " + response.error)
else:
self.write("Fetched URL: " + response.request.url)
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])