pool.py
This file
Path
httpcore/pool.py
126 lines · 3.9 KiB · Python
Last changed by
ConnectionsTom Christiebefore adoption86263fa
History of this fileTake it
ConnectionsTom Christiebefore adoption86263fa
lines 1–126why, one step back1import 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, stream=stream)47 return response4849 async def acquire_connection(50 self, url: URL, *, ssl: typing.Union[bool, ssl.SSLContext] = False51 ) -> Connection:52 connection = Connection(timeout=self.timeout)53 await connection.open(url.hostname, url.port, ssl=ssl)54 return connection5556 async def get_ssl_context(self, url: URL) -> typing.Union[bool, ssl.SSLContext]:57 if not url.is_secure:58 return False5960 if not hasattr(self, "ssl_context"):61 if not self.ssl_config.verify:62 self.ssl_context = self.get_ssl_context_no_verify()63 else:64 # Run the SSL loading in a threadpool, since it makes disk accesses.65 loop = asyncio.get_event_loop()66 self.ssl_context = await loop.run_in_executor(67 None, self.get_ssl_context_verify68 )6970 return self.ssl_context7172 def get_ssl_context_no_verify(self) -> ssl.SSLContext:73 """74 Return an SSL context for unverified connections.75 """76 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)77 context.options |= ssl.OP_NO_SSLv278 context.options |= ssl.OP_NO_SSLv379 context.options |= ssl.OP_NO_COMPRESSION80 context.set_default_verify_paths()81 return context8283 def get_ssl_context_verify(self) -> ssl.SSLContext:84 """85 Return an SSL context for verified connections.86 """87 cert = self.ssl_config.cert88 verify = self.ssl_config.verify8990 if isinstance(verify, bool):91 ca_bundle_path = DEFAULT_CA_BUNDLE_PATH92 elif os.path.exists(verify):93 ca_bundle_path = verify94 else:95 raise IOError(96 "Could not find a suitable TLS CA certificate bundle, "97 "invalid path: {}".format(verify)98 )99100 context = ssl.create_default_context()101 if os.path.isfile(ca_bundle_path):102 context.load_verify_locations(cafile=ca_bundle_path)103 elif os.path.isdir(ca_bundle_path):104 context.load_verify_locations(capath=ca_bundle_path)105106 if cert is not None:107 if isinstance(cert, str):108 context.load_cert_chain(certfile=cert)109 else:110 context.load_cert_chain(certfile=cert[0], keyfile=cert[1])111112 return context113114 async def close(self) -> None:115 self.is_closed = True116117 async def __aenter__(self) -> "ConnectionPool":118 return self119120 async def __aexit__(121 self,122 exc_type: typing.Type[BaseException] = None,123 exc_value: BaseException = None,124 traceback: TracebackType = None,125 ) -> None:126 await self.close()