SSL and TLS in Python requests

16,892

Requests uses the Python standard library ssl module under the hood - this supports various versions of SSL and TLS. You can tell requests to use a specific protocol (like TLSv1) by creating an HTTPAdapter that customizes the PoolManager instance that gets created.

I had to do something like this, but was bitten by the fact that we were also going via a proxy - in that case the init_poolmanager method isn't called, because it uses a ProxyManager instead. I used this:

class ForceTLSV1Adapter(adapters.HTTPAdapter):
    """Require TLSv1 for the connection"""
    def init_poolmanager(self, connections, maxsize, block=False):
        # This method gets called when there's no proxy.
        self.poolmanager = poolmanager.PoolManager(
            num_pools=connections,
            maxsize=maxsize,
            block=block,
            ssl_version=ssl.PROTOCOL_TLSv1,
        )

    def proxy_manager_for(self, proxy, **proxy_kwargs):
        # This method is called when there is a proxy.
        proxy_kwargs['ssl_version'] = ssl.PROTOCOL_TLSv1
        return super(ForceTLSV1Adapter, self).proxy_manager_for(proxy, **proxy_kwargs)
Share:
16,892
Javier Vazquez
Author by

Javier Vazquez

Salesforce and Python Developer in Ebury.

Updated on June 21, 2022

Comments

  • Javier Vazquez
    Javier Vazquez almost 2 years

    I'm using requests library for python, and I have a little problem: I'm connecting to a rest api and, in few days, this service will delete SSL connections, so I'll only can connect through TLS.

    Does someone know if requests allows TLS connection and how enable it?