Tornado Web App for Asynchronous Data Fetching

  • Share this:

Code introduction


This code creates a simple Tornado web application that asynchronously fetches web content from a specified URL and returns it.


Technology Stack : Tornado

Code Type : Web application

Code Difficulty : Intermediate


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

def fetch_random_data(url):
    class MainHandler(tornado.web.RequestHandler):
        def get(self):
            client = tornado.httpclient.AsyncHTTPClient()
            def handle_response(response):
                if response.error:
                    self.write("Error: " + str(response.error))
                else:
                    self.write("Response from " + url + ": " + response.body)
            client.fetch(url, callback=handle_response)

    def make_app():
        return tornado.web.Application([
            (r"/", MainHandler),
        ])

    if __name__ == "__main__":
        app = make_app()
        app.listen(8888)
        tornado.ioloop.IOLoop.current().start()                
              
Tags: