You can download this code by clicking the button below.
This code is now available for download.
This function uses Tornado's httpclient module to asynchronously fetch a random quote. It defines a handler that uses an asynchronous HTTP client to get a random quote from https://api.quotable.io/random API and returns the result to the requestor.
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_quote():
def make_handler(request, **kwargs):
client = tornado.httpclient.AsyncHTTPClient()
url = "https://api.quotable.io/random"
def on_response(response):
if response.code == 200:
quote = response.body.decode('utf-8')
return tornado.web.RequestHandler.write(self, quote)
else:
return tornado.web.RequestHandler.write(self, "Error fetching quote")
client.fetch(url, on_response)
return make_handler