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 can randomly access a predefined list of URLs and writes the URL of the received response to the client upon receiving it.
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://example.com",
"http://jsonplaceholder.typicode.com/todos/1",
"http://api.github.com/repos/tornado/tornado/issues"
]
client = tornado.httpclient.HTTPClient()
future = client.fetch(random.choice(urls))
return future
class MainHandler(tornado.web.RequestHandler):
def get(self):
future = fetch_random_url()
future.add_done_callback(self.on_fetch_done)
def on_fetch_done(self, future):
response = future.result()
self.write("Fetched URL: " + response.request.url)
self.finish()
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])