首页 > 解决方案 > 强制从 URL 下载图像的最长时间

问题描述

我正在尝试实现一种方法,该方法尝试尝试从 url 下载图像。为此,我使用 requests lib。我的代码的一个例子是:

while attempts < nmr_attempts:
        try:
            attempts += 1
            response = requests.get(self.basis_url, params=query_params, timeout=response_timeout)
        except Exception as e:
            pass

每次尝试的时间不能超过发出请求的“response_timeout”。但是似乎 timeout 变量没有做任何事情,因为它不尊重我自己给出的时间。

如何限制 response.get() 调用的最大阻塞时间。提前致谢

标签: pythonpython-3.xhttppython-requests

解决方案


您可以尝试关注(摆脱 try-except 块),看看它是否有帮助?except Exception可能正在抑制requests.get抛出的异常。

while attempts < nmr_attempts:
    response = requests.get(self.basis_url, params=query_params, timeout=response_timeout)

或者使用您的原始代码,您可以捕获requests.exceptions.ReadTimeout异常。如:

while attempts < nmr_attempts:
    try:
        attempts += 1
        response = requests.get(self.basis_url, params=query_params, timeout=response_timeout)
    except requests.exceptions.ReadTimeout as e:
        do_something()

推荐阅读