Tornado HTTP Request Handler with Asynchronous URL Fetching

  • Share this:

Code introduction


This function creates a Tornado HTTP request handler that sends a request to the URL specified by the first argument and returns the result as a JSON format. It also asynchronously sends an HTTP request to the URL specified by the second argument using Tornado's I/O loop.


Technology Stack : Tornado

Code Type : Web server

Code Difficulty : Intermediate


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

def fetch_random_url():
    urls = ["http://www.example.com", "http://www.google.com", "http://www.github.com"]
    url = random.choice(urls)
    return url

def xxx(arg1, arg2):
    handler = tornado.web.RequestHandler(self)
    handler.write(arg1)
    handler.finish()

    loop = tornado.ioloop.IOLoop.current()
    future = tornado.httpclient.HTTPClient().fetch(url=arg2)
    loop.run_in_executor(None, future)
    response = future.result()

    handler.set_header("Content-Type", "application/json")
    handler.finish()
    handler.write(json.dumps({"status": response.code, "body": response.body}))                
              
Tags: