Merge pull request #1 from encode/add-connections
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add connections
authored by Tom Christie · committed by GitHub · parents 665743a, ba1953c · Browse files · 12 files·+623 added−214 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+623 added−214 removed
- tests:+164 added−73 removed
- other:+459 added−141 removed
Provenance
- Commit
7626fe7- Tree
f496096- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent 1
665743a- Parent 2
ba1953c
12 files changed+623 added−214 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-132 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 .exceptions import ResponseClosed, StreamConsumed13-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- if stream:54- async def streaming_body():55- yield b"Hello, "56- yield b"world!"57- return Response(200, body=streaming_body)58- return Response(200, body=b"Hello, world!")59-60- async def close(self) -> None:61- self.is_closed = True62-63- async def __aenter__(self) -> "PoolManager":64- return self65-66- async def __aexit__(67- self,68- exc_type: typing.Type[BaseException] = None,69- exc_value: BaseException = None,70- traceback: TracebackType = None,71- ) -> None:72- await self.close()73-74-75-class Response:76- def __init__(77- self,78- status_code: int,79- *,80- headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),81- body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",82- on_close: typing.Callable = None,83- ):84- self.status_code = status_code85- self.headers = list(headers)86- self.on_close = on_close87- self.is_closed = False88- self.is_streamed = False89- if isinstance(body, bytes):90- self.is_closed = True91- self.body = body92- else:93- self.body_aiter = body94-95- async def read(self) -> bytes:96- if not hasattr(self, "body"):97- body = b""98- async for part in self.stream():99- body += part100- self.body = body101- return self.body102-103- async def stream(self) -> typing.AsyncIterator[bytes]:104- if hasattr(self, "body"):105- yield self.body106- else:107- if self.is_streamed:108- raise StreamConsumed()109- if self.is_closed:110- raise ResponseClosed()111- self.is_streamed = True112- async for part in self.body_aiter():113- yield part114- await self.close()115-116- async def close(self) -> None:117- if not self.is_closed:118- self.is_closed = True119- if self.on_close is not None:120- await self.on_close()121-122- async def __aenter__(self) -> "Response":123- return self124-125- async def __aexit__(126- self,127- exc_type: typing.Type[BaseException] = None,128- exc_value: BaseException = None,129- traceback: TracebackType = None,130- ) -> None:131- if not self.is_closed:132- 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()added:httpcore/connections.py+129 added
1+import asyncio2+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: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+28+ async def open(29+ self,30+ hostname: str,31+ port: int,32+ *,33+ ssl: typing.Union[bool, ssl.SSLContext] = False34+ ) -> None:35+ try:36+ 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+43+ 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+52+ headers = [host_header, content_length] + request.headers53+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:60+ async for data in request.stream():61+ event = h11.Data(data=data)62+ await self._send_event(event)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()69+ await self._send_event(event)70+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+ body_iter = self.body_iter()81+ return Response(status_code=status_code, headers=headers, body=body_iter)82+83+ # Get the response body.84+ body = b""85+ event = await self._receive_event()86+ while isinstance(event, h11.Data):87+ body += event.data88+ event = await self._receive_event()89+ assert isinstance(event, h11.EndOfMessage)90+ await self.close()91+92+ return Response(status_code=status_code, headers=headers, body=body)93+94+ async def body_iter(self) -> typing.AsyncIterator[bytes]:95+ event = await self._receive_event()96+ while isinstance(event, h11.Data):97+ yield event.data98+ event = await self._receive_event()99+ assert isinstance(event, h11.EndOfMessage)100+ await self.close()101+102+ async def _send_event(self, event: H11Event) -> None:103+ assert self.writer is not None104+105+ data = self.state.send(event)106+ self.writer.write(data)107+108+ async def _receive_event(self) -> H11Event:109+ assert self.reader is not None110+111+ event = self.state.next_event()112+113+ while event is h11.NEED_DATA:114+ try:115+ data = await asyncio.wait_for(116+ self.reader.read(2048), self.timeout.read_timeout117+ )118+ except asyncio.TimeoutError:119+ raise ReadTimeout()120+ self.state.receive_data(data)121+ event = self.state.next_event()122+123+ return event124+125+ async def close(self) -> None:126+ if self.writer is not None:127+ self.writer.close()128+ if hasattr(self.writer, "wait_closed"):129+ 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()added:httpcore/decoders.py+41 added
1+"""2+Handlers for Content-Encoding.3+"""4+5+6+class IdentityDecoder:7+ def decode(self, chunk: bytes) -> bytes:8+ return chunk9+10+ def flush(self) -> bytes:11+ return b""12+13+14+# class DeflateDecoder:15+# pass16+#17+#18+# class GZipDecoder:19+# pass20+#21+#22+# class BrotliDecoder:23+# pass24+#25+#26+# class MultiDecoder:27+# def __init__(self, children):28+# self.children = children29+#30+# def decode(self, chunk: bytes) -> bytes:31+# data = chunk32+# for child in children:33+# data = child.decode(data)34+# return data35+#36+# def flush(self) -> bytes:37+# data = b''38+# for child in children:39+# data = child.decode(data)40+# data = child.flush()41+# return dataadded: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+30 added
1+import asyncio2+3+import pytest4+from uvicorn.config import Config5+from uvicorn.main import Server6+7+8+async def app(scope, receive, send):9+ assert scope["type"] == "http"10+ await send(11+ {12+ "type": "http.response.start",13+ "status": 200,14+ "headers": [[b"content-type", b"text/plain"]],15+ }16+ )17+ await send({"type": "http.response.body", "body": b"Hello, world!"})18+19+20+@pytest.fixture21+async def server():22+ config = Config(app=app, lifespan="off")23+ server = Server(config=config)24+ task = asyncio.ensure_future(server.serve())25+ try:26+ while not server.started:27+ await asyncio.sleep(0.0001)28+ yield server29+ finally:30+ task.cancel()modified:tests/test_api.py+20 added-73 removed
2 unmodified lines3 import httpcore4 5 6 @pytest.mark.asyncio7-async def test_request():8- response = await httpcore.request("GET", "http://example.com")7+async def test_get(server):8+ async with httpcore.ConnectionPool() as http:9+ response = await http.request("GET", "http://127.0.0.1:8000/")10 assert response.status_code == 20011 assert response.body == b"Hello, world!"11- assert response.is_closed12 13 14 @pytest.mark.asyncio15-async def test_read_response():16- response = await httpcore.request("GET", "http://example.com")17-15+async def test_post(server):16+ async with httpcore.ConnectionPool() as http:17+ response = await http.request(18+ "POST", "http://127.0.0.1:8000/", body=b"Hello, world!"19+ )20 assert response.status_code == 20019- assert response.body == b"Hello, world!"20- assert response.is_closed21 22- body = await response.read()22 24- assert body == b"Hello, world!"25- assert response.body == b"Hello, world!"26- assert response.is_closed27-28-23 @pytest.mark.asyncio30-async def test_stream_response():31- response = await httpcore.request("GET", "http://example.com")32-24+async def test_stream_response(server):25+ async with httpcore.ConnectionPool() as http:26+ response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)27 assert response.status_code == 20034- assert response.body == b"Hello, world!"35- assert response.is_closed36-37- body = b''38- async for part in response.stream():39- body += part40-41- assert body == b"Hello, world!"42- assert response.body == b"Hello, world!"43- assert response.is_closed44-45-46-@pytest.mark.asyncio47-async def test_read_streaming_response():48- response = await httpcore.request("GET", "http://example.com", stream=True)49-50- assert response.status_code == 20051- assert not hasattr(response, 'body')28+ assert not hasattr(response, "body")52- assert not response.is_closed53-29 body = await response.read()55-30 assert body == b"Hello, world!"57- assert response.body == b"Hello, world!"58- assert response.is_closed31 32 33 @pytest.mark.asyncio62-async def test_stream_streaming_response():63- response = await httpcore.request("GET", "http://example.com", stream=True)34+async def test_stream_request(server):35+ async def hello_world():36+ yield b"Hello, "37+ yield b"world!"38 39+ async with httpcore.ConnectionPool() as http:40+ response = await http.request(41+ "POST", "http://127.0.0.1:8000/", body=hello_world()42+ )43 assert response.status_code == 20066- assert not hasattr(response, 'body')67- assert not response.is_closed68-69- body = b''70- async for part in response.stream():71- body += part72-73- assert body == b"Hello, world!"74- assert not hasattr(response, 'body')75- assert response.is_closed76-77-78-@pytest.mark.asyncio79-async def test_cannot_read_after_stream_consumed():80- response = await httpcore.request("GET", "http://example.com", stream=True)81-82- body = b''83- async for part in response.stream():84- body += part85-86- with pytest.raises(httpcore.StreamConsumed):87- await response.read()88-89-@pytest.mark.asyncio90-async def test_cannot_read_after_response_closed():91- response = await httpcore.request("GET", "http://example.com", stream=True)92-93- await response.close()94-95- with pytest.raises(httpcore.ResponseClosed):96- await response.read()added:tests/test_responses.py+114 added
1+import pytest2+3+import httpcore4+5+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+16+ return httpcore.Response(200, body=streaming_body())17+ return httpcore.Response(200, body=b"Hello, world!")18+19+20+http = MockHTTP()21+22+23+@pytest.mark.asyncio24+async def test_request():25+ response = await http.request("GET", "http://example.com")26+ assert response.status_code == 20027+ assert response.body == b"Hello, world!"28+ assert response.is_closed29+30+31+@pytest.mark.asyncio32+async def test_read_response():33+ response = await http.request("GET", "http://example.com")34+35+ assert response.status_code == 20036+ assert response.body == b"Hello, world!"37+ assert response.is_closed38+39+ body = await response.read()40+41+ assert body == b"Hello, world!"42+ assert response.body == b"Hello, world!"43+ assert response.is_closed44+45+46+@pytest.mark.asyncio47+async def test_stream_response():48+ response = await http.request("GET", "http://example.com")49+50+ assert response.status_code == 20051+ assert response.body == b"Hello, world!"52+ assert response.is_closed53+54+ body = b""55+ async for part in response.stream():56+ body += part57+58+ assert body == b"Hello, world!"59+ assert response.body == b"Hello, world!"60+ assert response.is_closed61+62+63+@pytest.mark.asyncio64+async def test_read_streaming_response():65+ response = await http.request("GET", "http://example.com", stream=True)66+67+ assert response.status_code == 20068+ assert not hasattr(response, "body")69+ assert not response.is_closed70+71+ body = await response.read()72+73+ assert body == b"Hello, world!"74+ assert response.body == b"Hello, world!"75+ assert response.is_closed76+77+78+@pytest.mark.asyncio79+async def test_stream_streaming_response():80+ response = await http.request("GET", "http://example.com", stream=True)81+82+ assert response.status_code == 20083+ assert not hasattr(response, "body")84+ assert not response.is_closed85+86+ body = b""87+ async for part in response.stream():88+ body += part89+90+ assert body == b"Hello, world!"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+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+111+ await response.close()112+113+ with pytest.raises(httpcore.ResponseClosed):114+ await response.read()modified:README.md+11 added-8 removed
61 unmodified lines6263646566666768697071727374757476777877798081808182838485868788898790919293947 unmodified lines10210310410510310610710810911013 unmodified lines12412512612712512812913013113221 unmodified lines61 unmodified lines
```pythonimport httpcore
http = httpcore.ConnectionPool()response = await httpcore.request('GET', 'http://example.com')response = await http.request('GET', 'http://example.com')assert response.status_code == 200assert response.body == b'Hello, world'```
Top-level API...
```pythonhttp = httpcore.ConnectionPool([ssl], [timeout], [limits])response = await httpcore.request(method, url, [headers], [body], [stream])response = await http.request(method, url, [headers], [body], [stream])```
Explicit PoolManager...ConnectionPool as a context-manager...
```pythonasync with httpcore.PoolManager([ssl], [timeout], [limits]) as pool: response = await pool.request(method, url, [headers], [body], [stream])async with httpcore.ConnectionPool([ssl], [timeout], [limits]) as http: response = await http.request(method, url, [headers], [body], [stream])```
Streaming...
```pythonhttp = httpcore.ConnectionPool()response = await httpcore.request(method, url, stream=True)response = await http.request(method, url, stream=True)async for part in response.stream(): ...```
7 unmodified lines
class GatewayServer: def __init__(self, base_url): self.base_url = base_url self.pool = httpcore.PoolManager() self.http = httpcore.ConnectionPool()
async def __call__(self, scope, receive, send): assert scope['type'] == 'http' path = scope['path']13 unmodified lines yield message.get('body', b'') if not message.get('more_body', False): break
response = await self.pool.request( response = await self.http.request( method, url, headers=headers, body=body, stream=True )
await send({21 unmodified linesmodified:requirements.txt+2 added
1+certifi2 h113 4 # Testing5 autoflake3 unmodified lines9 mypy10 pytest11 pytest-asyncio12 pytest-cov13+uvicorn