Python Requests超时参数被忽略

问题描述 投票:0回答:1

我正在使用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秒后打印一次超时异常,但我会以非常快的速度(一秒钟内多次)获得打印。

python python-2.7 http python-requests
1个回答
3
投票

当主持人无法到达时,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)
© www.soinside.com 2019 - 2024. All rights reserved.