You can download this code by clicking the button below.
This code is now available for download.
This function creates a web server based on Tornado that can handle HTTP requests and fetch content from a random URL.
Technology Stack : Tornado, HTTPClient
Code Type : Web Server
Code Difficulty : Intermediate
import random
import tornado.ioloop
import tornado.web
import tornado.httpclient
def fetch_random_url():
urls = ["http://www.example.com", "http://www.google.com", "http://www.github.com"]
return random.choice(urls)
def handle_request(request):
client = tornado.httpclient.AsyncHTTPClient()
response = client.fetch(fetch_random_url(), timeout=10)
return response.body
def random_url_handler(request):
return handle_request(request)
def xxx():
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write(handle_request(self))
def main():
application = tornado.web.Application([
(r"/random_url", random_url_handler),
(r"/", MainHandler),
])
application.listen(8888)
tornado.ioloop.IOLoop.current().start()
xxx()
# JSON Explanation