【问题标题】:Set timeout to an http request in Tornado在 Tornado 中为 http 请求设置超时
【发布时间】:2023-03-20 00:30:01
【问题描述】:

我有这部分代码:

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)

我在哪里做一个 http 请求。我会添加一个连接超时,以确保前面的代码被执行,所以我可以找到我的响应。

如何添加超时?我必须将它添加到 tornado.gen.Task 调用中吗?我不知道该怎么做。

【问题讨论】:

    标签: python timeout httprequest tornado


    【解决方案1】:

    使用HTTPRequest 类为请求添加超时,而不是仅仅将url 传递给fetch。试试:

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

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

    【讨论】:

    • 它不起作用。我将超时设置为 2.0 以加快响应速度,但不起作用。
    • 连接超时表示请求会在
    • 使用此代码,如果我打印响应,我有:HTTPResponse(code=200,request_time=0.30609703063964844,buffer=<io.BytesIO object at 0x276a1d0>,_body=None,time_info={},request=<tornado.httpclient.HTTPRequest object at 0x2764310>,effective_url='http://131.114.52.207:44444/ztc_config?netid=0&opcode_group=0&opcode=0&start=-20s&end=-1s',headers={'Content-Type': 'text/plain'},error=None) 如您所见,request_time=0.......
    • 如果我写 request = tornado.httpclient.HTTPRequest(url=como_url, connect_timeout=5.0, request_timeout=5.0) print request.connect_timeout 我得到 5.0 所以它可以工作......但不工作!
    • 您可能会明白这一点,但为了清楚起见:HTTPRequest.request_timeout 只是限制值,而HTTPResponse.request_time 是完成请求的实际时间。
    【解决方案2】:

    我也遇到过这个问题,有时超时不起作用。 原因是SimpleAsyncHTTPClient.max_clients 达到最大值。

    SimpleAsyncHTTPClient.fetch_impl 中,如果self.active 的数量大于max_clients 的数量,则不分配timeout_handle

    所以你添加增加龙卷风实例或max_clients,可以解决它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      • 2021-10-07
      • 1970-01-01
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多