Skip to content
Myr

config.py

This file

Path

httpcore/config.py

172 lines · 5.2 KiB · Python

Last changed by

Merge pull request #12 from encode/refactorTom Christiebefore adoption39eb55b

History of this file

Take it

1import asyncio2import os3import ssl4import typing56import certifi789class SSLConfig:10    """11    SSL Configuration.12    """1314    def __init__(15        self,16        *,17        cert: typing.Union[None, str, typing.Tuple[str, str]] = None,18        verify: typing.Union[str, bool] = True,19    ):20        self.cert = cert21        self.verify = verify2223    def __eq__(self, other: typing.Any) -> bool:24        return (25            isinstance(other, self.__class__)26            and self.cert == other.cert27            and self.verify == other.verify28        )2930    def __hash__(self) -> int:31        as_tuple = (self.cert, self.verify)32        return hash(as_tuple)3334    def __repr__(self) -> str:35        class_name = self.__class__.__name__36        return f"{class_name}(cert={self.cert}, verify={self.verify})"3738    async def load_ssl_context(self) -> ssl.SSLContext:39        if not hasattr(self, "ssl_context"):40            if not self.verify:41                self.ssl_context = self.load_ssl_context_no_verify()42            else:43                # Run the SSL loading in a threadpool, since it makes disk accesses.44                loop = asyncio.get_event_loop()45                self.ssl_context = await loop.run_in_executor(46                    None, self.load_ssl_context_verify47                )4849        return self.ssl_context5051    def load_ssl_context_no_verify(self) -> ssl.SSLContext:52        """53        Return an SSL context for unverified connections.54        """55        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)56        context.options |= ssl.OP_NO_SSLv257        context.options |= ssl.OP_NO_SSLv358        context.options |= ssl.OP_NO_COMPRESSION59        context.set_default_verify_paths()60        return context6162    def load_ssl_context_verify(self) -> ssl.SSLContext:63        """64        Return an SSL context for verified connections.65        """66        if isinstance(self.verify, bool):67            ca_bundle_path = DEFAULT_CA_BUNDLE_PATH68        elif os.path.exists(self.verify):69            ca_bundle_path = self.verify70        else:71            raise IOError(72                "Could not find a suitable TLS CA certificate bundle, "73                "invalid path: {}".format(self.verify)74            )7576        context = ssl.create_default_context()77        if os.path.isfile(ca_bundle_path):78            context.load_verify_locations(cafile=ca_bundle_path)79        elif os.path.isdir(ca_bundle_path):80            context.load_verify_locations(capath=ca_bundle_path)8182        if self.cert is not None:83            if isinstance(self.cert, str):84                context.load_cert_chain(certfile=self.cert)85            else:86                context.load_cert_chain(certfile=self.cert[0], keyfile=self.cert[1])8788        return context899091class TimeoutConfig:92    """93    Timeout values.94    """9596    def __init__(97        self,98        timeout: float = None,99        *,100        connect_timeout: float = None,101        read_timeout: float = None,102        pool_timeout: float = None,103    ):104        if timeout is not None:105            # Specified as a single timeout value106            assert connect_timeout is None107            assert read_timeout is None108            assert pool_timeout is None109            connect_timeout = timeout110            read_timeout = timeout111            pool_timeout = timeout112113        self.timeout = timeout114        self.connect_timeout = connect_timeout115        self.read_timeout = read_timeout116        self.pool_timeout = pool_timeout117118    def __eq__(self, other: typing.Any) -> bool:119        return (120            isinstance(other, self.__class__)121            and self.connect_timeout == other.connect_timeout122            and self.read_timeout == other.read_timeout123            and self.pool_timeout == other.pool_timeout124        )125126    def __hash__(self) -> int:127        as_tuple = (self.connect_timeout, self.read_timeout, self.pool_timeout)128        return hash(as_tuple)129130    def __repr__(self) -> str:131        class_name = self.__class__.__name__132        if self.timeout is not None:133            return f"{class_name}(timeout={self.timeout})"134        return f"{class_name}(connect_timeout={self.connect_timeout}, read_timeout={self.read_timeout}, pool_timeout={self.pool_timeout})"135136137class PoolLimits:138    """139    Limits on the number of connections in a connection pool.140    """141142    def __init__(143        self,144        *,145        soft_limit: typing.Optional[int] = None,146        hard_limit: typing.Optional[int] = None,147    ):148        self.soft_limit = soft_limit149        self.hard_limit = hard_limit150151    def __eq__(self, other: typing.Any) -> bool:152        return (153            isinstance(other, self.__class__)154            and self.soft_limit == other.soft_limit155            and self.hard_limit == other.hard_limit156        )157158    def __hash__(self) -> int:159        as_tuple = (self.soft_limit, self.hard_limit)160        return hash(as_tuple)161162    def __repr__(self) -> str:163        class_name = self.__class__.__name__164        return (165            f"{class_name}(soft_limit={self.soft_limit}, hard_limit={self.hard_limit})"166        )167168169DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)170DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)171DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100)172DEFAULT_CA_BUNDLE_PATH = certifi.where()