You can download this code by clicking the button below.
This code is now available for download.
This code creates a Tornado web server that can randomly fetch data from a predefined list of URLs and return the data to the client.
Technology Stack : Tornado, HTTPClient
Code Type : Tornado Web Server
Code Difficulty : Intermediate
import tornado.ioloop
import tornado.web
import tornado.httpclient
import random
def fetch_random_data(url):
# Create HTTP client
client = tornado.httpclient.HTTPClient()
# Fetch data from the given URL
response = client.fetch(url)
# Return the response body
return response.body
def random_data_handler(request):
# Generate a random URL from a predefined list
urls = ["http://jsonplaceholder.typicode.com/todos/1", "http://jsonplaceholder.typicode.com/posts/1", "http://jsonplaceholder.typicode.com/users/1"]
random_url = random.choice(urls)
# Fetch data from the random URL
data = fetch_random_data(random_url)
# Return the fetched data as JSON
return tornado.web.HTTPResponse(
body=data,
headers={"Content-Type": "application/json"}
)
def main():
# Create a Tornado web application
application = tornado.web.Application([
(r"/random_data", random_data_handler)
])
# Start the Tornado I/O loop
application.listen(8888)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()