Search code examples
pythontimeouthttprequesttornado

Set timeout to an http request in Tornado


I have this part of code:

como_url = "".join(['http://', options.como_address, ':', options.como_port, 
                        '/ztc_config?netid=0&opcode_group=0&opcode=0&start=-20s&end=-1s'])

http_client = AsyncHTTPClient()
response = yield tornado.gen.Task(http_client.fetch, como_url)

where I do an http request. I would add a connection timeout, to be sure that the previous code is been executed, so I can find my response.

How can I add the timeout? I have to add it into the tornado.gen.Task call? I don't know how to do.


Solution

  • Use the HTTPRequest class to add a timeout to the request, instead of just passing the url to fetch. Try:

    request = tornado.httpclient.HTTPRequest(url=como_url, connect_timeout=20.0, request_timeout=20.0)
    response = yield tornado.gen.Task(http_client.fetch, request)
    

    See http://www.tornadoweb.org/en/branch2.4/httpclient.html#tornado.httpclient.HTTPRequest