Tornado Asynchronous API Resource Fetcher

  • Share this:

Code introduction


This function uses the tornado library to asynchronously fetch a random resource from a public API and prints the response body to the console.


Technology Stack : tornado, httpclient, httputil

Code Type : Function

Code Difficulty : Intermediate


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

def fetch_random_resource():
    def handle_response(response):
        if response.code == 200:
            print("Response body:", response.body)
        else:
            print("Error:", response.code)

    http_client = tornado.httpclient.AsyncHTTPClient()
    url = "http://jsonplaceholder.typicode.com/todos/{}".format(random.randint(1, 100))
    http_client.fetch(url, handle_response)

def xxx(arg1, arg2):
    # This function fetches a random resource from a public API and prints the response body
    io_loop = tornado.ioloop.IOLoop.current()
    io_loop.run_in_executor(None, fetch_random_resource)