Tornado-based Asynchronous URL Fetcher

  • Share this:

Code introduction


This function uses the tornado library to asynchronously fetch the content of a URL and then prints out the response content or error message. It uses tornado's HTTP client and I/O loop.


Technology Stack : tornado, HTTP client, asynchronous programming

Code Type : Web Server and HTTP Client

Code Difficulty : Intermediate


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

def fetch_random_url(url):
    def handle_response(response):
        if response.error:
            print("Error fetching URL:", response.error)
        else:
            print("URL response:", response.body)

    http_client = tornado.httpclient.AsyncHTTPClient()
    http_client.fetch(url, callback=handle_response)

    loop = tornado.ioloop.IOLoop.current()
    loop.start()

    loop.stop()

# JSON representation of the code