Home  >  Article  >  Backend Development  >  How to Disable Certificate Verification in Python Requests?

How to Disable Certificate Verification in Python Requests?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 15:38:03754browse

How to Disable Certificate Verification in Python Requests?

Disable Certificate Verification in Python Requests

When encountering an expired certificate error while making HTTPS requests with requests, a common solution is to disable the security certificate check.

Solution 1: Using verify=False

As mentioned in the documentation, you can pass verify=False to disable certificate verification.

<code class="python">import requests
requests.post(url='https://foo.example', data={'bar':'baz'}, verify=False)</code>

Solution 2: Monkey Patching requests (Context Manager)

For more advanced usage, you can use a context manager to monkey patch requests and disable certificate verification for all requests within the context.

<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>

Usage:

<code class="python">with no_ssl_verification():
    requests.get('https://wrong.host.badssl.example/')</code>

Note that this context manager closes all open adapters after leaving it to avoid unexpected behavior due to cached connections.

The above is the detailed content of How to Disable Certificate Verification in Python Requests?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn