Set timeout to an http request in Tornado

2019-07-22 01:14发布

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.

2条回答
别忘想泡老子
2楼-- · 2019-07-22 01:43

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

查看更多
看我几分像从前
3楼-- · 2019-07-22 01:43

I have also encountered this problem, sometimes timeout doesn't work. Reason is SimpleAsyncHTTPClient.max_clients reach max value.

In SimpleAsyncHTTPClient.fetch_impl, if number of self.active greater than number of max_clients then timeout_handle be assigned none.

So you add increase tornado instance or max_clients, can solve it

查看更多
登录 后发表回答