Asynchronous HTTP Request Fetch with Tornado and Random URL Selection

  • Share this:

Code introduction


This function uses the httpclient module from the tornado library to make asynchronous HTTP requests. It randomly selects a URL from a predefined list, then initiates a request using AsyncHTTPClient, and defines two callback functions to handle responses and errors.


Technology Stack : tornado, httpclient

Code Type : Asynchronous HTTP request

Code Difficulty : Intermediate


                
                    
import tornado.ioloop
import tornado.web
import tornado.httpclient
import random

def fetch_random_url():
    urls = [
        "http://example.com",
        "http://random.org",
        "http://jsonplaceholder.typicode.com/todos/1"
    ]
    http_client = tornado.httpclient.AsyncHTTPClient()
    def handle_response(response):
        print("Response received:", response.body)
    def error_handler(error):
        print("Error:", error)
    url = random.choice(urls)
    http_client.fetch(url, callback=handle_response, error_callback=error_handler)