Asynchronous URL Fetching with Tornado HTTPClient

  • Share this:

Code introduction


This function uses the Tornado library's HTTPClient to asynchronously fetch a URL's response and prints out the response status code and content.


Technology Stack : tornado, HTTPClient

Code Type : Function

Code Difficulty : Intermediate


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

def fetch_url(url):
    def handle_response(response):
        if response.error:
            print("Error fetching URL: ", response.error)
        else:
            print("Response status: ", response.code)
            print("Response body: ", response.body)

    http_client = tornado.httpclient.HTTPClient()
    request = tornado.httpclient.HTTPRequest(url=url, callback=handle_response)
    http_client.fetch(request)

# JSON representation of the code