Disabling Security Certificate Verification in Python Requests
When interacting with HTTPS endpoints using the Python requests library, you may encounter errors related to invalid SSL certificates. To alleviate this issue, you can disable certificate verification within the request.
According to the official documentation, you can achieve this by setting the verify parameter to False. This instructs requests to bypass certificate verification.
<code class="python">import requests requests.post(url='https://foo.example', data={'bar': 'baz'}, verify=False)</code>
Alternatively, for third-party modules that may handle SSL verification, you can employ a context manager to suppress warnings and disable verification. This involves replacing the requests.Session.merge_environment_settings method with a custom version that sets verify to False by default.
<code class="python">import warnings import contextlib import requests from urllib3.exceptions import InsecureRequestWarning old_merge_environment_settings = requests.Session.merge_environment_settings @contextlib.contextmanager def no_ssl_verification(): opened_adapters = set() def merge_environment_settings(self, url, proxies, stream, verify, cert): opened_adapters.add(self.get_adapter(url)) settings = old_merge_environment_settings(self, url, proxies, stream, verify, cert) settings['verify'] = False return settings requests.Session.merge_environment_settings = merge_environment_settings try: with warnings.catch_warnings(): warnings.simplefilter('ignore', InsecureRequestWarning) yield finally: requests.Session.merge_environment_settings = old_merge_environment_settings for adapter in opened_adapters: try: adapter.close() except: pass</code>
You can use this context manager as follows:
<code class="python">with no_ssl_verification(): requests.get('https://wrong.host.badssl.example/') print('It works') requests.get('https://wrong.host.badssl.example/', verify=False) print('It resets back')</code>
It's important to note that this solution affects all requests made during the context manager's scope. Hence, unless explicitly specified, subsequent requests will also bypass certificate verification.
The above is the detailed content of How to Disable Security Certificate Verification in Python Requests?. For more information, please follow other related articles on the PHP Chinese website!