Reputation: 544
I know it's possible to disable InsecureRequestWarning
but I need the opposite, I want to either catch it or make the request abort and throw an exception if this warning is present.
Upvotes: 0
Views: 421
Reputation: 21
I thought I had a solution for this in the following code but it doesn't because specifying verify=False on the request will unconditionally produce the warning regardless of if the URL has a valid cert or not. Unless there is a way to produce that warning without having to specify verify=False, then I believe the answer to the question is simply '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
Upvotes: 0
Reputation: 544
I've solved it with warnings.filterwarnings("error")
, which turns warnings into errors so they can be caught with try catch.
Upvotes: 1