强制设置从 URL 下载图像的最长时间



我正在尝试实现一种方法,该方法尝试尝试从url下载图像。为此,我正在使用请求库。我的代码示例是:

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"提出请求。但是,超时变量似乎没有做任何事情,因为它不尊重我自己给出的时间。

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

你能尝试跟随(摆脱 try-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()

最新更新