urllib3 不会在来自端点的 400 Bad Request 响应上引发异常

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

我正在尝试使用 urllib3 发出请求并处理端点抛出的任何错误

我的代码和期望如下:

import urllib3
...
try:
  response = http.request('POST', url, headers=headers, body=encoded_data)
  print(response.status) # => 400

except urllib3.exceptions.HTTPError as e:
  print(e) # Expect this to be reached but isn't

except Exception as e:
  print(e) # This also isn't hit telling me an exception isn't thrown at all

我故意扭曲了我的请求以抛出 400 并期望 urllib3 与 urllib 类似地处理该请求:

from urllib import request, error
...
try:
  response = request.urlopen(request, data=encoded_data)
  content = response.read()

except error.HTTPError as e:
  print(e) # This is hit in the case of a 400+ response

如有任何帮助,我们将不胜感激,谢谢

python api urllib3
1个回答
0
投票

这是因为

urllib3
urllib

上的行为不同

urllib3 默认情况下不会引发 HTTP 错误状态代码(如 400、404、500 等)的异常。相反,它返回一个包含状态代码的响应对象。所以你应该检查 status.code 并看看它是否等于 200。

urllib 将以与您期望的方式相同的方式运行并引发异常。如果您希望将错误作为异常引发,可以考虑使用 requests 库

© www.soinside.com 2019 - 2024. All rights reserved.