Connections
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by Tom Christie · parent 6a4376b · Browse files · 13 files·+464 added−184 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+464 added−184 removed
- tests:+87 added−10 removed
- other:+377 added−174 removed
Provenance
- Commit
86263fa- Tree
5559e4a- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
6a4376b
13 files changed+464 added−184 removed
modified:httpcore/__init__.py+2 added-1 removed
1-from .api import PoolManager, Response, request1 from .config import PoolLimits, SSLConfig, TimeoutConfig2+from .datastructures import URL, Request, Response3 from .exceptions import ResponseClosed, StreamConsumed4+from .pool import ConnectionPool5 6 __version__ = "0.0.2"deleted:httpcore/api.py-67 removed
1-import typing2-from types import TracebackType3-4-from .config import (5- DEFAULT_POOL_LIMITS,6- DEFAULT_SSL_CONFIG,7- DEFAULT_TIMEOUT_CONFIG,8- PoolLimits,9- SSLConfig,10- TimeoutConfig,11-)12-from .models import Response13-14-15-async def request(16- method: str,17- url: str,18- *,19- headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),20- body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",21- stream: bool = False,22- ssl: SSLConfig = DEFAULT_SSL_CONFIG,23- timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,24-) -> Response:25- async with PoolManager(ssl=ssl, timeout=timeout) as pool:26- return await pool.request(27- method=method, url=url, headers=headers, body=body, stream=stream28- )29-30-31-class PoolManager:32- def __init__(33- self,34- *,35- ssl: SSLConfig = DEFAULT_SSL_CONFIG,36- timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,37- limits: PoolLimits = DEFAULT_POOL_LIMITS,38- ):39- self.ssl = ssl40- self.timeout = timeout41- self.limits = limits42- self.is_closed = False43-44- async def request(45- self,46- method: str,47- url: str,48- *,49- headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),50- body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",51- stream: bool = False,52- ) -> Response:53- raise NotImplementedError()54-55- async def close(self) -> None:56- self.is_closed = True57-58- async def __aenter__(self) -> "PoolManager":59- return self60-61- async def __aexit__(62- self,63- exc_type: typing.Type[BaseException] = None,64- exc_value: BaseException = None,65- traceback: TracebackType = None,66- ) -> None:67- await self.close()modified:httpcore/config.py+3 added
1 import typing2 3+import certifi4 5+6 class SSLConfig:7 """8 SSL Configuration.9 """43 unmodified lines53 54 DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)55 DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)56 DEFAULT_POOL_LIMITS = PoolLimits(max_hosts=10, conns_per_host=10, hard_limit=False)57+DEFAULT_CA_BUNDLE_PATH = certifi.where()modified:httpcore/connections.py+87 added-29 removed
1-from config import TimeoutConfig2-1 import asyncio4-import h112 import ssl3+import typing4 5+import h116 7+from .config import TimeoutConfig8+from .datastructures import Request, Response9+from .exceptions import ConnectTimeout, ReadTimeout10+11+H11Event = typing.Union[12+ h11.Request,13+ h11.Response,14+ h11.InformationalResponse,15+ h11.Data,16+ h11.EndOfMessage,17+ h11.ConnectionClosed,18+]19+20+21 class Connection:9- def __init__(self):22+ def __init__(self, timeout: TimeoutConfig):23 self.reader = None24 self.writer = None25 self.state = h11.Connection(our_role=h11.CLIENT)26+ self.timeout = timeout27 14- async def open(self, host: str, port: int, ssl: ssl.SSLContext):28+ async def open(29+ self,30+ hostname: str,31+ port: int,32+ *,33+ ssl: typing.Union[bool, ssl.SSLContext] = False34+ ) -> None:35 try:16- self.reader, self.writer = await asyncio.wait_for(17- asyncio.open_connection(host, port, ssl=ssl), timeout36+ self.reader, self.writer = await asyncio.wait_for( # type: ignore37+ asyncio.open_connection(hostname, port, ssl=ssl),38+ self.timeout.connect_timeout,39 )40 except asyncio.TimeoutError:41 raise ConnectTimeout()42 22- async def send(self, request: Request) -> Response:23- method = request.method43+ async def send(self, request: Request, stream: bool=False) -> Response:44+ method = request.method.encode()45+ target = request.url.target46+ host_header = (b"host", request.url.netloc.encode("ascii"))47+ if request.is_streaming:48+ content_length = (b"transfer-encoding", b"chunked")49+ else:50+ content_length = (b"content-length", str(len(request.body)).encode())51 25- target = request.url.path26- if request.url.query:27- target += "?" + request.url.query52+ headers = [host_header, content_length] + request.headers53 29- headers = [30- ("host", request.url.netloc)31- ] += request.headers32-33- # Send the request method, path/query, and headers.54+ # Start sending the request.55 event = h11.Request(method=method, target=target, headers=headers)56 await self._send_event(event)57 58 # Send the request body.59 if request.is_streaming:39- async for data in request.raw():60+ async for data in request.stream():61 event = h11.Data(data=data)62 await self._send_event(event)42- else:63+ elif request.body:64 event = h11.Data(data=request.body)65 await self._send_event(event)66 67 # Finalize sending the request.68 event = h11.EndOfMessage()48- await connection.send_event(event)69+ await self._send_event(event)70 50- async def _send_event(self, message):51- data = self.state.send(message)71+ # Start getting the response.72+ event = await self._receive_event()73+ if isinstance(event, h11.InformationalResponse):74+ event = await self._receive_event()75+ assert isinstance(event, h11.Response)76+ status_code = event.status_code77+ headers = event.headers78+79+ if stream:80+ return Response(status_code=status_code, headers=headers, body=self.body_iter())81+82+ # Get the response body.83+ body = b""84+ event = await self._receive_event()85+ while isinstance(event, h11.Data):86+ body += event.data87+ event = await self._receive_event()88+ assert isinstance(event, h11.EndOfMessage)89+ await self.close()90+91+ return Response(status_code=status_code, headers=headers, body=body)92+93+ async def body_iter(self) -> typing.Iterable[bytes]:94+ event = await self._receive_event()95+ while isinstance(event, h11.Data):96+ yield event.data97+ event = await self._receive_event()98+ assert isinstance(event, h11.EndOfMessage)99+ await self.close()100+101+ async def _send_event(self, event: H11Event) -> None:102+ assert self.writer is not None103+104+ data = self.state.send(event)105 self.writer.write(data)106 54- async def _receive_event(self, timeout):107+ async def _receive_event(self) -> H11Event:108+ assert self.reader is not None109+110 event = self.state.next_event()111 57- while type(event) is h11.NEED_DATA:112+ while event is h11.NEED_DATA:113 try:59- data = await asyncio.wait_for(self.reader.read(2048), timeout)114+ data = await asyncio.wait_for(115+ self.reader.read(2048), self.timeout.read_timeout116+ )117 except asyncio.TimeoutError:118 raise ReadTimeout()119 self.state.receive_data(data)120 event = self.state.next_event()121 122 return event123 124+ async def close(self) -> None:67- async def close(self):68- self.writer.close()69- if hasattr(self.writer, "wait_closed"):70- await self.writer.wait_closed()125+ if self.writer is not None:126+ self.writer.close()127+ if hasattr(self.writer, "wait_closed"):128+ await self.writer.wait_closed()added:httpcore/datastructures.py+145 added
1+import typing2+from urllib.parse import urlsplit3+4+from .decoders import IdentityDecoder5+from .exceptions import ResponseClosed, StreamConsumed6+7+8+class URL:9+ def __init__(self, url: str = "") -> None:10+ self.components = urlsplit(url)11+ if not self.components.scheme:12+ raise ValueError("No scheme included in URL.")13+ if self.components.scheme not in ("http", "https"):14+ raise ValueError('URL scheme must be "http" or "https".')15+ if not self.components.hostname:16+ raise ValueError("No hostname included in URL.")17+18+ @property19+ def scheme(self) -> str:20+ return self.components.scheme21+22+ @property23+ def netloc(self) -> str:24+ return self.components.netloc25+26+ @property27+ def path(self) -> str:28+ return self.components.path29+30+ @property31+ def query(self) -> str:32+ return self.components.query33+34+ @property35+ def hostname(self) -> str:36+ return self.components.hostname37+38+ @property39+ def port(self) -> int:40+ port = self.components.port41+ if port is None:42+ return {"https": 443, "http": 80}[self.scheme]43+ return port44+45+ @property46+ def target(self) -> str:47+ path = self.path or "/"48+ query = self.query49+ if query:50+ return path + "?" + query51+ return path52+53+ @property54+ def is_secure(self) -> bool:55+ return self.components.scheme == "https"56+57+58+class Request:59+ def __init__(60+ self,61+ method: str,62+ url: URL,63+ *,64+ headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),65+ body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",66+ ):67+ self.method = method68+ self.url = url69+ self.headers = list(headers)70+ if isinstance(body, bytes):71+ self.is_streaming = False72+ self.body = body73+ else:74+ self.is_streaming = True75+ self.body_aiter = body76+77+ async def stream(self) -> typing.AsyncIterator[bytes]:78+ assert self.is_streaming79+80+ async for part in self.body_aiter:81+ yield part82+83+84+class Response:85+ def __init__(86+ self,87+ status_code: int,88+ *,89+ headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),90+ body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",91+ on_close: typing.Callable = None,92+ ):93+ self.status_code = status_code94+ self.headers = list(headers)95+ self.on_close = on_close96+ self.is_closed = False97+ self.is_streamed = False98+ self.decoder = IdentityDecoder()99+ if isinstance(body, bytes):100+ self.is_closed = True101+ self.body = body102+ else:103+ self.body_aiter = body104+105+ async def read(self) -> bytes:106+ """107+ Read and return the response content.108+ """109+ if not hasattr(self, "body"):110+ body = b""111+ async for part in self.stream():112+ body += part113+ self.body = body114+ return self.body115+116+ async def stream(self) -> typing.AsyncIterator[bytes]:117+ """118+ A byte-iterator over the decoded response content.119+ This will allow us to handle gzip, deflate, and brotli encoded responses.120+ """121+ if hasattr(self, "body"):122+ yield self.body123+ else:124+ async for chunk in self.raw():125+ yield self.decoder.decode(chunk)126+ yield self.decoder.flush()127+128+ async def raw(self) -> typing.AsyncIterator[bytes]:129+ """130+ A byte-iterator over the raw response content.131+ """132+ if self.is_streamed:133+ raise StreamConsumed()134+ if self.is_closed:135+ raise ResponseClosed()136+ self.is_streamed = True137+ async for part in self.body_aiter:138+ yield part139+ await self.close()140+141+ async def close(self) -> None:142+ if not self.is_closed:143+ self.is_closed = True144+ if self.on_close is not None:145+ await self.on_close()modified:httpcore/decoders.py+1 added-1 removed
6 unmodified lines7 def decode(self, chunk: bytes) -> bytes:8 return chunk9 10 def flush(self) -> bytes:11- return b''11+ return b""12 13 14 # class DeflateDecoder:15 # pass26 unmodified linesdeleted:httpcore/models.py-68 removed
1-import typing2-3-from .decoders import IdentityDecoder4-from .exceptions import ResponseClosed, StreamConsumed5-6-7-class Response:8- def __init__(9- self,10- status_code: int,11- *,12- headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),13- body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",14- on_close: typing.Callable = None,15- ):16- self.status_code = status_code17- self.headers = list(headers)18- self.on_close = on_close19- self.is_closed = False20- self.is_streamed = False21- self.decoder = IdentityDecoder()22- if isinstance(body, bytes):23- self.is_closed = True24- self.body = body25- else:26- self.body_aiter = body27-28- async def read(self) -> bytes:29- """30- Read and return the response content.31- """32- if not hasattr(self, "body"):33- body = b""34- async for part in self.stream():35- body += part36- self.body = body37- return self.body38-39- async def stream(self):40- """41- A byte-iterator over the decoded response content.42- This will allow us to handle gzip, deflate, and brotli encoded responses.43- """44- if hasattr(self, "body"):45- yield self.body46- else:47- async for chunk in self.raw():48- yield self.decoder.decode(chunk)49- yield self.decoder.flush()50-51- async def raw(self) -> typing.AsyncIterator[bytes]:52- """53- A byte-iterator over the raw response content.54- """55- if self.is_streamed:56- raise StreamConsumed()57- if self.is_closed:58- raise ResponseClosed()59- self.is_streamed = True60- async for part in self.body_aiter():61- yield part62- await self.close()63-64- async def close(self) -> None:65- if not self.is_closed:66- self.is_closed = True67- if self.on_close is not None:68- await self.on_close()added:httpcore/pool.py+126 added
1+import asyncio2+import os3+import ssl4+import typing5+from types import TracebackType6+7+from .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+)16+from .connections import Connection17+from .datastructures import URL, Request, Response18+19+20+class 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 = False32+33+ 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 response48+49+ 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 connection55+56+ async def get_ssl_context(self, url: URL) -> typing.Union[bool, ssl.SSLContext]:57+ if not url.is_secure:58+ return False59+60+ 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+ )69+70+ return self.ssl_context71+72+ 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 context82+83+ 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.verify89+90+ 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+ )99+100+ 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)105+106+ 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])111+112+ return context113+114+ async def close(self) -> None:115+ self.is_closed = True116+117+ async def __aenter__(self) -> "ConnectionPool":118+ return self119+120+ 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()added:tests/conftest.py+34 added
1+import asyncio2+import json3+4+import pytest5+from uvicorn.config import Config6+from uvicorn.main import Server7+8+9+async def app(scope, receive, send):10+ assert scope['type'] == 'http'11+ await send({12+ 'type': 'http.response.start',13+ 'status': 200,14+ 'headers': [15+ [b'content-type', b'text/plain'],16+ ]17+ })18+ await send({19+ 'type': 'http.response.body',20+ 'body': b'Hello, world!',21+ })22+23+24+@pytest.fixture25+async def server():26+ config = Config(app=app, lifespan="off")27+ server = Server(config=config)28+ task = asyncio.ensure_future(server.serve())29+ try:30+ while not server.started:31+ await asyncio.sleep(0.0001)32+ yield server33+ finally:34+ task.cancel()modified:tests/test_api.py+38 added
1+import pytest2+import httpcore3+4+5+@pytest.mark.asyncio6+async def test_get(server):7+ async with httpcore.ConnectionPool() as http:8+ response = await http.request('GET', "http://127.0.0.1:8000/")9+ assert response.status_code == 20010+ assert response.body == b'Hello, world!'11+12+13+@pytest.mark.asyncio14+async def test_post(server):15+ async with httpcore.ConnectionPool() as http:16+ response = await http.request('POST', "http://127.0.0.1:8000/", body=b"Hello, world!")17+ assert response.status_code == 20018+19+20+@pytest.mark.asyncio21+async def test_stream_response(server):22+ async with httpcore.ConnectionPool() as http:23+ response = await http.request('GET', "http://127.0.0.1:8000/", stream=True)24+ assert response.status_code == 20025+ assert not hasattr(response, 'body')26+ body = await response.read()27+ assert body == b'Hello, world!'28+29+30+@pytest.mark.asyncio31+async def test_stream_request(server):32+ async def hello_world():33+ yield b"Hello, "34+ yield b"world!"35+36+ async with httpcore.ConnectionPool() as http:37+ response = await http.request('POST', "http://127.0.0.1:8000/", body=hello_world())38+ assert response.status_code == 200modified:tests/test_responses.py+15 added-10 removed
1 unmodified line2 3 import httpcore4 5 6-class MockRequests(httpcore.PoolManager):7- async def request(self, method, url, *, headers = (), body = b'', stream = False) -> httpcore.Response:6+class MockHTTP(httpcore.ConnectionPool):7+ async def request(8+ self, method, url, *, headers=(), body=b"", stream=False9+ ) -> httpcore.Response:10 if stream:11+12 async def streaming_body():13 yield b"Hello, "14 yield b"world!"15+12- return httpcore.Response(200, body=streaming_body)16+ return httpcore.Response(200, body=streaming_body())17 return httpcore.Response(200, body=b"Hello, world!")18 19 16-http = MockRequests()20+http = MockHTTP()21 22 23 @pytest.mark.asyncio24 async def test_request():25 unmodified lines50 assert response.status_code == 20051 assert response.body == b"Hello, world!"52 assert response.is_closed53 50- body = b''54+ body = b""55 async for part in response.stream():56 body += part57 58 assert body == b"Hello, world!"5 unmodified lines64 async def test_read_streaming_response():65 response = await http.request("GET", "http://example.com", stream=True)66 67 assert response.status_code == 20064- assert not hasattr(response, 'body')68+ assert not hasattr(response, "body")69 assert not response.is_closed70 71 body = await response.read()72 6 unmodified lines79 async def test_stream_streaming_response():80 response = await http.request("GET", "http://example.com", stream=True)81 82 assert response.status_code == 20079- assert not hasattr(response, 'body')83+ assert not hasattr(response, "body")84 assert not response.is_closed85 82- body = b''86+ body = b""87 async for part in response.stream():88 body += part89 90 assert body == b"Hello, world!"87- assert not hasattr(response, 'body')91+ assert not hasattr(response, "body")92 assert response.is_closed93 94 95 @pytest.mark.asyncio96 async def test_cannot_read_after_stream_consumed():97 response = await http.request("GET", "http://example.com", stream=True)98 95- body = b''99+ body = b""100 async for part in response.stream():101 body += part102 103 with pytest.raises(httpcore.StreamConsumed):104 await response.read()105 106+107 @pytest.mark.asyncio108 async def test_cannot_read_after_response_closed():109 response = await http.request("GET", "http://example.com", stream=True)110 4 unmodified linesmodified:README.md+11 added-8 removed
61 unmodified lines62 63 ```python64 import httpcore65 66+http = httpcore.ConnectionPool()66-response = await httpcore.request('GET', 'http://example.com')67+response = await http.request('GET', 'http://example.com')68 assert response.status_code == 20069 assert response.body == b'Hello, world'70 ```71 72 Top-level API...73 74 ```python75+http = httpcore.ConnectionPool([ssl], [timeout], [limits])74-response = await httpcore.request(method, url, [headers], [body], [stream])76+response = await http.request(method, url, [headers], [body], [stream])77 ```78 77-Explicit PoolManager...79+ConnectionPool as a context-manager...80 81 ```python80-async with httpcore.PoolManager([ssl], [timeout], [limits]) as pool:81- response = await pool.request(method, url, [headers], [body], [stream])82+async with httpcore.ConnectionPool([ssl], [timeout], [limits]) as http:83+ response = await http.request(method, url, [headers], [body], [stream])84 ```85 86 Streaming...87 88 ```python89+http = httpcore.ConnectionPool()87-response = await httpcore.request(method, url, stream=True)90+response = await http.request(method, url, stream=True)91 async for part in response.stream():92 ...93 ```94 7 unmodified lines102 103 class GatewayServer:104 def __init__(self, base_url):105 self.base_url = base_url103- self.pool = httpcore.PoolManager()106+ self.http = httpcore.ConnectionPool()107 108 async def __call__(self, scope, receive, send):109 assert scope['type'] == 'http'110 path = scope['path']13 unmodified lines124 yield message.get('body', b'')125 if not message.get('more_body', False):126 break127 125- response = await self.pool.request(128+ response = await self.http.request(129 method, url, headers=headers, body=body, stream=True130 )131 132 await send({21 unmodified linesmodified:requirements.txt+2 added
1+certifi2 h113 4 # Testing5 autoflake3 unmodified lines9 mypy10 pytest11 pytest-asyncio12 pytest-cov13+uvicorn