Search code examples
requesttornadohttpresponsehttp-getasynchttpclient

How to find the request for a particular response while using tornado library?


This is a reduced version of the code.I and making over 100 requests using http_client.fetch, I am getting the responses in random order,It is really important for me to know which response is for which request that I made.What changes should I make in order to achieve this?

from tornado import ioloop, httpclient
def handle_request(response):
    jsonobject_ticker = json.loads( response.body, object_hook= JSONObject)
    currency_price=jsonobject_ticker.result.Last
    print "{0:.9f}".format(currency_price)
    global i
    i -= 1
    if i == 0:
        ioloop.IOLoop.instance().stop()

def check_for_pump():
    for index in range (len(shortlisted)):      
        market=shortlisted[index]
        print market

        http_client = httpclient.AsyncHTTPClient()
        global i
        i += 1
        http_client.fetch(get_ticker_url(shortlisted[index]), handle_request, method='GET')

Solution

  • The HTTPResponse object has a "request" property, so you can just access response.request in your callback.

    More generally, however, if you wanted to pass specific data to a callback you can use a "partial":

    from functools import partial
    
    def handle_request(data, response):
        ...
    
    data = "foo"
    callback = partial(data, handle_request)
    http_client.fetch(url, callback)
    

    You don't need this technique in this case, but it's good to know how to pass data to a callback in Tornado.