Implementing an asynchronous client with AsyncHTTPClient

Tornado includes a class called AsyncHTTPClient, which performs HTTP requests asynchronously. The first thing is to create our application, which will inherit from application. Then, we will run an HTTP server that supports our application. Next, we will indicate in which port we want the server to listen. Finally, we will launch the event loop, which will listen to requests with the IOLoop.current().start() instruction.

In the following example, we are using the fetch method of AsyncHTTPClient, which specifies the method or function that will be called when the HTTP request is complete as a callback parameter. In this example, we specified the on_response method as the callback. Also note the use of the @tornado.web.asynchronous decorator and the call to self.finish() at the end of the callback response method.

You can find the following code in the tornado_request_async.py file:

#!/usr/bin/python3

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

class Handler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
http_client = tornado.httpclient.AsyncHTTPClient()
http_client.fetch("https://www.google.com/search?q=python", callback=self.on_response)

def on_response(self, response):
self.write(response.body)
self.finish()

In the previous code block, we define our Handler class that extends from tornado.web.RequestHandler. This class contains the asynchronous get() method and on_response() method, which is called when getting a response from the http_client object.

In the following code block we define our main program, where we define the event loop and our application managed by the Handler class:

if __name__ == '__main__':
app = tornado.web.Application([ tornado.web.url(r"/", Handler)])
app.listen(8080)
tornado.ioloop.IOLoop.current().start()

If we execute this script and go to (http://localhost:8080), we will see the response related to the Python search in the Google domain.

Another way to implement an asynchronous client is to create a TornadoAsyncClient() class with a method that handle requests. In this example, we can see this implementation where the URL is requested as a parameter in the script.

You can find the following code in the tornado_async_client.py file:

#!/usr/bin/python3

import argparse
import tornado.ioloop
import tornado.httpclient

class TornadoAsyncClient():
def handle_request(self,response):
if response.error:
print ("Error:", response.error)
else:
print(response.body)
tornado.ioloop.IOLoop.instance().stop()

In the previous code block, we define our TornadoAsyncClient class that manages the request and the event loop.

In the next code block we define our run_server() method and main program , where we instantiate the TornadoAsyncClient class, starting the event loop, and set the url parameter to do the request:

def run_server(url):
tornadoAsync = TornadoAsyncClient()
http_client = tornado.httpclient.AsyncHTTPClient()
http_client.fetch(url, tornadoAsync.handle_request)
tornado.ioloop.IOLoop.instance().start()

if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Tornado async client')
parser.add_argument('--url', action="store", dest="url", type=str, required=True)
given_args = parser.parse_args()
url = given_args.url
run_server(url)

The previous execution script will create a Tornado server that will execute requests asynchronously. To execute it, it is necessary to pass the URL that we want to obtain the response from as a parameter:

usage: tornado_async_client.py [-h] --url URL
tornado_async_client.py: error: the following arguments are required: --url

When you run the preceding command, you will see the response body of the URL that is passed as a parameter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset