Skip to content
Myr

pool.py

This file

Path

httpcore/pool.py

131 lines · 4.0 KiB · Python

Last changed by

Rejig response streaming/closingTom Christiebefore adoption63d73ad

History of this file

Take it

1import asyncio2import os3import ssl4import typing5from types import TracebackType67from .config import (8    DEFAULT_CA_BUNDLE_PATH,9    DEFAULT_POOL_LIMITS,10    DEFAULT_SSL_CONFIG,11    DEFAULT_TIMEOUT_CONFIG,12    PoolLimits,13    SSLConfig,14    TimeoutConfig,15)16from .connections import Connection17from .datastructures import URL, Request, Response181920class ConnectionPool:21    def __init__(22        self,23        *,24        ssl: SSLConfig = DEFAULT_SSL_CONFIG,25        timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,26        limits: PoolLimits = DEFAULT_POOL_LIMITS,27    ):28        self.ssl_config = ssl29        self.timeout = timeout30        self.limits = limits31        self.is_closed = False3233    async def request(34        self,35        method: str,36        url: str,37        *,38        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),39        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",40        stream: bool = False,41    ) -> Response:42        parsed_url = URL(url)43        request = Request(method, parsed_url, headers=headers, body=body)44        ssl_context = await self.get_ssl_context(parsed_url)45        connection = await self.acquire_connection(parsed_url, ssl=ssl_context)46        response = await connection.send(request)47        if not stream:48            try:49                await response.read()50            finally:51                await response.close()52        return response5354    async def acquire_connection(55        self, url: URL, *, ssl: typing.Union[bool, ssl.SSLContext] = False56    ) -> Connection:57        connection = Connection(timeout=self.timeout)58        await connection.open(url.hostname, url.port, ssl=ssl)59        return connection6061    async def get_ssl_context(self, url: URL) -> typing.Union[bool, ssl.SSLContext]:62        if not url.is_secure:63            return False6465        if not hasattr(self, "ssl_context"):66            if not self.ssl_config.verify:67                self.ssl_context = self.get_ssl_context_no_verify()68            else:69                # Run the SSL loading in a threadpool, since it makes disk accesses.70                loop = asyncio.get_event_loop()71                self.ssl_context = await loop.run_in_executor(72                    None, self.get_ssl_context_verify73                )7475        return self.ssl_context7677    def get_ssl_context_no_verify(self) -> ssl.SSLContext:78        """79        Return an SSL context for unverified connections.80        """81        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)82        context.options |= ssl.OP_NO_SSLv283        context.options |= ssl.OP_NO_SSLv384        context.options |= ssl.OP_NO_COMPRESSION85        context.set_default_verify_paths()86        return context8788    def get_ssl_context_verify(self) -> ssl.SSLContext:89        """90        Return an SSL context for verified connections.91        """92        cert = self.ssl_config.cert93        verify = self.ssl_config.verify9495        if isinstance(verify, bool):96            ca_bundle_path = DEFAULT_CA_BUNDLE_PATH97        elif os.path.exists(verify):98            ca_bundle_path = verify99        else:100            raise IOError(101                "Could not find a suitable TLS CA certificate bundle, "102                "invalid path: {}".format(verify)103            )104105        context = ssl.create_default_context()106        if os.path.isfile(ca_bundle_path):107            context.load_verify_locations(cafile=ca_bundle_path)108        elif os.path.isdir(ca_bundle_path):109            context.load_verify_locations(capath=ca_bundle_path)110111        if cert is not None:112            if isinstance(cert, str):113                context.load_cert_chain(certfile=cert)114            else:115                context.load_cert_chain(certfile=cert[0], keyfile=cert[1])116117        return context118119    async def close(self) -> None:120        self.is_closed = True121122    async def __aenter__(self) -> "ConnectionPool":123        return self124125    async def __aexit__(126        self,127        exc_type: typing.Type[BaseException] = None,128        exc_value: BaseException = None,129        traceback: TracebackType = None,130    ) -> None:131        await self.close()