【问题标题】:Python Requests timeout parameter is being ignoredPython 请求超时参数被忽略
【发布时间】:2019-04-22 12:01:50
【问题描述】:

我正在使用 Python 2.7,我希望每个请求在几秒钟后超时,但请求几乎立即超时。以下是我的代码。

requestsTimeout = 5
link = 'http://' + IP + '/api/v1.0/system/info'
while (1):
    try:
        return requests.get(link, timeout = requestsTimeout)
    except requests.exceptions.RequestException as e:
        log._print0(_printID, 'getting DAQ Info' ,str(e)) # just printing
        time.sleep(0.1)

现在,如果我断开 wifi 连接,我应该每 5 秒打印一次超时异常,但打印速度非常快(一秒内多次)。

【问题讨论】:

  • while True 超过 while (1)
  • 我每天都在 C 和 python 之间切换,处理不同的语法真的很烦人,尤其是当你必须写 'True' 而不是 'true' 时!
  • 您遇到的真的是超时异常吗?我假设如果您断开 wifi 连接会发生另一个异常。
  • 正如 Reductio 所说,你应该得到一个不同的错误,我认为那将是一个 ConnectionError
  • 您可以只使用裸露的Exception 而不是requests.exceptions.RequestException,其中包括所有异常,其中还包括导致问题的requests.exceptions.ConnectionError

标签: python python-2.7 http python-requests


【解决方案1】:

当主机无法访问时,ConnectionError 会在没有timeout 设置的等待时间的情况下引发。你可以通过单独处理这个异常来克服这个问题:

requestsTimeout = 5
link = 'http://' + IP + '/api/v1.0/system/info'
while True:
    try:
        return requests.get(link, timeout=requestsTimeout)
    except requests.exceptions.ConnectionError as e:
        time.sleep(requestsTimeout)
    except requests.exceptions.RequestException as e:
        log._print0(_printID, 'getting DAQ Info' ,str(e)) # just printing
        time.sleep(0.1)

【讨论】:

  • 是的,确实是连接错误,不是超时错误,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-17
  • 2019-03-31
  • 1970-01-01
  • 2015-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多