是否有办法从python请求中捕获InsecureRequestWarning

q5iwbnjs  于 2023-02-03  发布在  Python
关注(0)|答案(2)|浏览(117)

我知道禁用InsecureRequestWarning是可能的,但我需要相反的,我希望要么捕获它,要么使请求中止,并在出现此警告时抛出异常。

w8f9ii69

w8f9ii691#

我已经用warnings.filterwarnings("error")解决了这个问题,它将警告转换为错误,这样就可以用try catch捕获它们。

dwthyt8l

dwthyt8l2#

我以为我在下面的代码中有一个解决这个问题的方法,但是它没有,因为在请求中指定 verify=False 将无条件地产生警告,而不管URL是否有一个有效的证书。除非有一种方法可以在不指定 verify=False 的情况下产生警告,否则我相信这个问题的答案是简单的'no'。

>>> import requests
... import warnings
... try:
...    requests.post("https://self-signed.badssl.com", data={"key": "value"})
... except requests.RequestException as ex:
...    print("See if our RequestException is caused by certification verification...")
...    warnings.filterwarnings("error")
...    try:
...       requests.post("https://self-signed.badssl.com", data={"key": "value"}, verify=False)
...    except requests.packages.urllib3.exceptions.InsecureRequestWarning as ex:
...       print("Handled InsecureRequestWarning:\n\t{}".format(ex))
...    finally:
...       warnings.resetwarnings()
... 
See if our RequestException is caused by certification verification...
Handled InsecureRequestWarning:
    Unverified HTTPS request is being made to host 'self-signed.badssl.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings

相关问题