Using Tornado#s AsyncHTTPClient to Fetch Random URLs

  • Share this:

Code introduction


This function uses Tornado's AsyncHTTPClient to asynchronously fetch content from a random URL.


Technology Stack : Tornado, AsyncHTTPClient

Code Type : Asynchronous HTTP request

Code Difficulty : Intermediate


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

def fetch_random_url():
    """
    Fetches content from a random URL using Tornado's HTTP client.
    """
    urls = ["http://example.com", "http://python.org", "http://google.com"]
    client = tornado.httpclient.AsyncHTTPClient()
    def handle_response(response):
        print("Response from URL:", response.request.url)
        print("Status code:", response.code)
        print("Response body length:", len(response.body))
    client.fetch(random.choice(urls), callback=handle_response)