Truckin' on
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 0ca1c84 · Browse files · 11 files·+381 added−269 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+381 added−269 removed
- tests:+33 added−26 removed
- other:+348 added−243 removed
Provenance
- Commit
6b60d95- Tree
6ba0dfa- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
0ca1c84
11 files changed+381 added−269 removed
modified:httpcore/dispatch/connection_pool.py+5 added-5 removed
87 unmodified lines88 self,89 *,90 ssl: SSLConfig = DEFAULT_SSL_CONFIG,91 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,92- limits: PoolLimits = DEFAULT_POOL_LIMITS,92+ pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,93 ):94 self.ssl = ssl95 self.timeout = timeout96- self.limits = limits96+ self.pool_limits = pool_limits97 self.is_closed = False98 99- self.max_connections = PoolSemaphore(limits)99+ self.max_connections = PoolSemaphore(pool_limits)100 self.keepalive_connections = ConnectionStore()101 self.active_connections = ConnectionStore()102 103 @property35 unmodified lines139 if connection.is_closed:140 self.active_connections.remove(connection)141 self.max_connections.release()142 elif (143- self.limits.soft_limit is not None144- and self.num_connections > self.limits.soft_limit143+ self.pool_limits.soft_limit is not None144+ and self.num_connections > self.pool_limits.soft_limit145 ):146 self.active_connections.remove(connection)147 self.max_connections.release()148 await connection.close()10 unmodified linesmodified:httpcore/__init__.py+1 added-1 removed
22 unmodified lines23 from .interfaces import Adapter24 from .models import URL, Headers, Origin, Request, Response25 from .status_codes import codes26 from .streams import BaseReader, BaseWriter, Protocol, Reader, Writer, connect27-from .sync import SyncClient, SyncConnectionPool27+from .sync import SyncClient28 29 __version__ = "0.2.1"modified:httpcore/client.py+4 added-2 removed
21 unmodified lines22 def __init__(23 self,24 ssl: SSLConfig = DEFAULT_SSL_CONFIG,25 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,26- limits: PoolLimits = DEFAULT_POOL_LIMITS,26+ pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,27 max_redirects: int = DEFAULT_MAX_REDIRECTS,28 ):29- connection_pool = ConnectionPool(ssl=ssl, timeout=timeout, limits=limits)29+ connection_pool = ConnectionPool(30+ ssl=ssl, timeout=timeout, pool_limits=pool_limits31+ )32 cookie_adapter = CookieAdapter(dispatch=connection_pool)33 auth_adapter = AuthenticationAdapter(dispatch=cookie_adapter)34 redirect_adapter = RedirectAdapter(35 dispatch=auth_adapter, max_redirects=max_redirects211 unmodified linesmodified:httpcore/models.py+5 added-1 removed
433 unmodified lines434 on_close: typing.Callable = None,435 request: Request = None,436 history: typing.List["Response"] = None,437 ):438+ try:439+ # Use a StatusCode IntEnum if possible, for a nicer representation.440+ self.status_code = codes(status_code)441+ except ValueError:438- self.status_code = status_code442+ self.status_code = status_code443 self.reason_phrase = reason_phrase or get_reason_phrase(status_code)444 self.protocol = protocol445 self.headers = Headers(headers)446 175 unmodified linesmodified:httpcore/streams.py+4 added-4 removed
72 unmodified lines73 self.stream_writer.close()74 75 76 class PoolSemaphore(BasePoolSemaphore):77- def __init__(self, limits: PoolLimits):78- self.limits = limits77+ def __init__(self, pool_limits: PoolLimits):78+ self.pool_limits = pool_limits79 80 @property81 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:82 if not hasattr(self, "_semaphore"):83- max_connections = self.limits.hard_limit83+ max_connections = self.pool_limits.hard_limit84 if max_connections is None:85 self._semaphore = None86 else:87 self._semaphore = asyncio.BoundedSemaphore(value=max_connections)2 unmodified lines90 async def acquire(self) -> None:91 if self.semaphore is None:92 return93 94- timeout = self.limits.pool_timeout94+ timeout = self.pool_limits.pool_timeout95 try:96 await asyncio.wait_for(self.semaphore.acquire(), timeout)97 except asyncio.TimeoutError:98 raise PoolTimeout()35 unmodified linesmodified:httpcore/sync.py+197 added-16 removed
1 import asyncio2 import typing3 from types import TracebackType4 5-from .config import SSLConfig, TimeoutConfig6-from .dispatch.connection_pool import ConnectionPool7-from .interfaces import Adapter8-from .models import URL, Headers, Response5+from .client import Client6+from .config import (7+ DEFAULT_MAX_REDIRECTS,8+ DEFAULT_POOL_LIMITS,9+ DEFAULT_SSL_CONFIG,10+ DEFAULT_TIMEOUT_CONFIG,11+ PoolLimits,12+ SSLConfig,13+ TimeoutConfig,14+)15+from .models import (16+ URL,17+ ByteOrByteStream,18+ Headers,19+ HeaderTypes,20+ Request,21+ Response,22+ URLTypes,23+)24 25 26 class SyncResponse:27 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):43 unmodified lines71 return self._loop.run_until_complete(self._response.close())72 73 74 class SyncClient:60- def __init__(self, adapter: Adapter):61- self._client = adapter75+ def __init__(76+ self,77+ ssl: SSLConfig = DEFAULT_SSL_CONFIG,78+ timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,79+ pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,80+ max_redirects: int = DEFAULT_MAX_REDIRECTS,81+ ) -> None:82+ self._client = Client(83+ ssl=ssl,84+ timeout=timeout,85+ pool_limits=pool_limits,86+ max_redirects=max_redirects,87+ )88 self._loop = asyncio.new_event_loop()89 90 def request(91 self,92 method: str,67- url: typing.Union[str, URL],93+ url: URLTypes,94 *,69- headers: typing.List[typing.Tuple[bytes, bytes]] = [],70- body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",71- **options: typing.Any95+ content: ByteOrByteStream = b"",96+ headers: HeaderTypes = None,97+ stream: bool = False,98+ allow_redirects: bool = True,99+ ssl: SSLConfig = None,100+ timeout: TimeoutConfig = None,101 ) -> SyncResponse:102 response = self._loop.run_until_complete(74- self._client.request(method, url, headers=headers, body=body, **options)103+ self._client.request(104+ method,105+ url,106+ content=content,107+ headers=headers,108+ stream=stream,109+ allow_redirects=allow_redirects,110+ ssl=ssl,111+ timeout=timeout,112+ )113 )114 return SyncResponse(response, self._loop)115 116+ def get(117+ self,118+ url: URLTypes,119+ *,120+ headers: HeaderTypes = None,121+ stream: bool = False,122+ allow_redirects: bool = True,123+ ssl: SSLConfig = None,124+ timeout: TimeoutConfig = None,125+ ) -> SyncResponse:126+ return self.request(127+ "GET",128+ url,129+ headers=headers,130+ stream=stream,131+ allow_redirects=allow_redirects,132+ ssl=ssl,133+ timeout=timeout,134+ )135+136+ def options(137+ self,138+ url: URLTypes,139+ *,140+ headers: HeaderTypes = None,141+ stream: bool = False,142+ allow_redirects: bool = True,143+ ssl: SSLConfig = None,144+ timeout: TimeoutConfig = None,145+ ) -> SyncResponse:146+ return self.request(147+ "OPTIONS",148+ url,149+ headers=headers,150+ stream=stream,151+ allow_redirects=allow_redirects,152+ ssl=ssl,153+ timeout=timeout,154+ )155+156+ def head(157+ self,158+ url: URLTypes,159+ *,160+ headers: HeaderTypes = None,161+ stream: bool = False,162+ allow_redirects: bool = False, # Note: Differs to usual default.163+ ssl: SSLConfig = None,164+ timeout: TimeoutConfig = None,165+ ) -> SyncResponse:166+ return self.request(167+ "HEAD",168+ url,169+ headers=headers,170+ stream=stream,171+ allow_redirects=allow_redirects,172+ ssl=ssl,173+ timeout=timeout,174+ )175+176+ def post(177+ self,178+ url: URLTypes,179+ *,180+ content: ByteOrByteStream = b"",181+ headers: HeaderTypes = None,182+ stream: bool = False,183+ allow_redirects: bool = True,184+ ssl: SSLConfig = None,185+ timeout: TimeoutConfig = None,186+ ) -> SyncResponse:187+ return self.request(188+ "POST",189+ url,190+ content=content,191+ headers=headers,192+ stream=stream,193+ allow_redirects=allow_redirects,194+ ssl=ssl,195+ timeout=timeout,196+ )197+198+ def put(199+ self,200+ url: URLTypes,201+ *,202+ content: ByteOrByteStream = b"",203+ headers: HeaderTypes = None,204+ stream: bool = False,205+ allow_redirects: bool = True,206+ ssl: SSLConfig = None,207+ timeout: TimeoutConfig = None,208+ ) -> SyncResponse:209+ return self.request(210+ "PUT",211+ url,212+ content=content,213+ headers=headers,214+ stream=stream,215+ allow_redirects=allow_redirects,216+ ssl=ssl,217+ timeout=timeout,218+ )219+220+ def patch(221+ self,222+ url: URLTypes,223+ *,224+ content: ByteOrByteStream = b"",225+ headers: HeaderTypes = None,226+ stream: bool = False,227+ allow_redirects: bool = True,228+ ssl: SSLConfig = None,229+ timeout: TimeoutConfig = None,230+ ) -> SyncResponse:231+ return self.request(232+ "PATCH",233+ url,234+ content=content,235+ headers=headers,236+ stream=stream,237+ allow_redirects=allow_redirects,238+ ssl=ssl,239+ timeout=timeout,240+ )241+242+ def delete(243+ self,244+ url: URLTypes,245+ *,246+ content: ByteOrByteStream = b"",247+ headers: HeaderTypes = None,248+ stream: bool = False,249+ allow_redirects: bool = True,250+ ssl: SSLConfig = None,251+ timeout: TimeoutConfig = None,252+ ) -> SyncResponse:253+ return self.request(254+ "DELETE",255+ url,256+ content=content,257+ headers=headers,258+ stream=stream,259+ allow_redirects=allow_redirects,260+ ssl=ssl,261+ timeout=timeout,262+ )263+264 def close(self) -> None:265 self._loop.run_until_complete(self._client.close())266 267 def __enter__(self) -> "SyncClient":5 unmodified lines273 exc_value: BaseException = None,274 traceback: TracebackType = None,275 ) -> None:276 self.close()91-92-93-def SyncConnectionPool(*args: typing.Any, **kwargs: typing.Any) -> SyncClient:94- client = ConnectionPool(*args, **kwargs) # type: ignore95- return SyncClient(client)modified:tests/dispatch/test_connection_pools.py+2 added-2 removed
36 unmodified lines37 async def test_soft_limit(server):38 """39 The soft_limit config should limit the maximum number of keep-alive connections.40 """41- limits = httpcore.PoolLimits(soft_limit=1)41+ pool_limits = httpcore.PoolLimits(soft_limit=1)42 43- async with httpcore.ConnectionPool(limits=limits) as http:43+ async with httpcore.ConnectionPool(pool_limits=pool_limits) as http:44 response = await http.request("GET", "http://127.0.0.1:8000/")45 assert len(http.active_connections) == 046 assert len(http.keepalive_connections) == 147 79 unmodified linesmodified:tests/test_sync.py+10 added-10 removed
23 unmodified lines24 25 26 @threadpool27 def test_get(server):28- with httpcore.SyncConnectionPool() as http:29- response = http.request("GET", "http://127.0.0.1:8000/")28+ with httpcore.SyncClient() as http:29+ response = http.get("http://127.0.0.1:8000/")30 assert response.status_code == 20031 assert response.content == b"Hello, world!"32 assert response.text == "Hello, world!"33 34 35 @threadpool36 def test_post(server):37- with httpcore.SyncConnectionPool() as http:38- response = http.request("POST", "http://127.0.0.1:8000/", body=b"Hello, world!")37+ with httpcore.SyncClient() as http:38+ response = http.post("http://127.0.0.1:8000/", content=b"Hello, world!")39 assert response.status_code == 20040 assert response.reason_phrase == "OK"41 42 43 @threadpool44 def test_stream_response(server):45- with httpcore.SyncConnectionPool() as http:46- response = http.request("GET", "http://127.0.0.1:8000/", stream=True)45+ with httpcore.SyncClient() as http:46+ response = http.get("http://127.0.0.1:8000/", stream=True)47 assert response.status_code == 20048 content = response.read()49 assert content == b"Hello, world!"50 51 52 @threadpool53 def test_stream_iterator(server):54- with httpcore.SyncConnectionPool() as http:55- response = http.request("GET", "http://127.0.0.1:8000/", stream=True)54+ with httpcore.SyncClient() as http:55+ response = http.get("http://127.0.0.1:8000/", stream=True)56 assert response.status_code == 20057 body = b""58 for chunk in response.stream():59 body += chunk1 unmodified line61 62 63 @threadpool64 def test_raw_iterator(server):65- with httpcore.SyncConnectionPool() as http:66- response = http.request("GET", "http://127.0.0.1:8000/", stream=True)65+ with httpcore.SyncClient() as http:66+ response = http.get("http://127.0.0.1:8000/", stream=True)67 assert response.status_code == 20068 body = b""69 for chunk in response.raw():70 body += chunk1 unmodified linemodified:tests/test_timeouts.py+21 added-14 removed
1 import pytest2 3-import httpcore3+from httpcore import (4+ Client,5+ ConnectTimeout,6+ PoolLimits,7+ PoolTimeout,8+ ReadTimeout,9+ TimeoutConfig,10+)11 12 13 @pytest.mark.asyncio14 async def test_read_timeout(server):8- timeout = httpcore.TimeoutConfig(read_timeout=0.0001)15+ timeout = TimeoutConfig(read_timeout=0.0001)16 10- async with httpcore.ConnectionPool(timeout=timeout) as http:11- with pytest.raises(httpcore.ReadTimeout):12- await http.request("GET", "http://127.0.0.1:8000/slow_response")17+ async with Client(timeout=timeout) as client:18+ with pytest.raises(ReadTimeout):19+ await client.get("http://127.0.0.1:8000/slow_response")20 21 22 @pytest.mark.asyncio23 async def test_connect_timeout(server):17- timeout = httpcore.TimeoutConfig(connect_timeout=0.0001)24+ timeout = TimeoutConfig(connect_timeout=0.0001)25 19- async with httpcore.ConnectionPool(timeout=timeout) as http:20- with pytest.raises(httpcore.ConnectTimeout):26+ async with Client(timeout=timeout) as client:27+ with pytest.raises(ConnectTimeout):28 # See https://stackoverflow.com/questions/100841/22- await http.request("GET", "http://10.255.255.1/")29+ await client.get("http://10.255.255.1/")30 31 32 @pytest.mark.asyncio33 async def test_pool_timeout(server):27- limits = httpcore.PoolLimits(hard_limit=1, pool_timeout=0.0001)34+ pool_limits = PoolLimits(hard_limit=1, pool_timeout=0.0001)35 29- async with httpcore.ConnectionPool(limits=limits) as http:30- response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)36+ async with Client(pool_limits=pool_limits) as client:37+ response = await client.get("http://127.0.0.1:8000/", stream=True)38 32- with pytest.raises(httpcore.PoolTimeout):33- await http.request("GET", "http://localhost:8000/")39+ with pytest.raises(PoolTimeout):40+ await client.get("http://localhost:8000/")41 42 await response.read()deleted:API.md-90 removed
1-Client(...)2-3- .request(method, url, ...)4-5- .get(url, ...)6- .options(url, ...)7- .head(url, ...)8- .post(url, ...)9- .put(url, ...)10- .patch(url, ...)11- .delete(url, ...)12-13- .prepare_request(request)14- .send(request, ...)15- .close()16-17-18-Adapter()19-20- .prepare_request(request)21- .send(request)22- .close()23-24-25-+ EnvironmentAdapter26-+ RedirectAdapter27-+ CookieAdapter28-+ AuthAdapter29-+ ConnectionPool30- + HTTPConnection31- + HTTP11Connection32- + HTTP2Connection33-34-35-36-Response(...)37- .status_code - int38- .reason_phrase - str39- .protocol - "HTTP/2" or "HTTP/1.1"40- .url - URL41- .headers - Headers42-43- .content - bytes44- .text - str45- .encoding - str46- .json() - Any47-48- .read() - bytes49- .stream() - bytes iterator50- .raw() - bytes iterator51- .close() - None52-53- .is_redirect - bool54- .request - Request55- .cookies - Cookies56- .history - List[Response]57-58- .raise_for_status()59- .next()60-61-62-Request(...)63- .method64- .url65- .headers66-67- ...68-69-70-Headers71-72-URL73-74-Origin75-76-Cookies77-78-79-# Sync80-81-SyncClient82-SyncResponse83-SyncRequest84-SyncAdapter85-86-87-88-SSE89-HTTP/2 server push support90-Concurrencymodified:README.md+132 added-124 removed
1 # HTTPCore2 3-A low-level async HTTP library.3+A proposal for [requests III](https://github.com/kennethreitz/requests3).4 5-## Proposed functionality5+## Feature support6 7-* Support for streaming requests and responses. (Done)8-* Support for connection pooling. (Done)9-* gzip, deflate, and brotli decoding. (Done)10-* SSL verification. (Done)11-* Proxy support. (Not done)12-* HTTP/2 support. (Not done)13-* Support *both* async and sync operations. (Done)7+* `HTTP/1.1` and `HTTP/2` Support.8+* `async`/`await` support for non-thread-blocking HTTP requests.9+* Fully type annotated.10+* 100% test coverage. *TODO - We're on ~97% right now*11 15-## Motivation12+Plus all the standard features of requests...13 17-Some of the trickier remaining issues on `requests-async` such as request/response streaming, connection pooling, proxy support, would require a fully async variant of urllib3. I considered and started work on a straight port of `urllib3-async`, but having started to dive into it, my judgement is that a from-scratch implementation will be less overall work to achieve.14+* International Domains and URLs15+* Keep-Alive & Connection Pooling16+* Sessions with Cookie Persistence *TODO*17+* Browser-style SSL Verification18+* Basic/Digest Authentication *TODO*19+* Elegant Key/Value Cookies *TODO*20+* Automatic Decompression21+* Automatic Content Decoding22+* Unicode Response Bodies23+* Multipart File Uploads *TODO*24+* HTTP(S) Proxy Support *TODO*25+* Connection Timeouts26+* Streaming Downloads27+* .netrc Support *TODO*28+* Chunked Requests29 19-The intent is that this library could be the low-level implementation, that `requests-async` would then wrap up.20-21-## Credit22-23-* Some inspiration from the design-work of `urllib3`, but redone from scratch, and built as an async-first library.24-* Dependant on the absolutely excellent `h11` package.25-* Uses the `certifi` package for the default SSL verification.26-30 ## Usage31 32 Making a request:33 34 ```python32-import httpcore33-34-http = httpcore.ConnectionPool()35-response = await http.request('GET', 'http://example.com')36-assert response.status_code == 20037-assert response.body == b'Hello, world'35+>>> import httpcore36+>>>37+>>> client = httpcore.Client()38+>>> response = await client.get('http://example.com')39+>>> response.status_code40+<StatusCode.ok: 200>41+>>> response.text42+'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>\n...'43 ```44 40-Top-level API:45+Alternatively, thread-synchronous requests:46 47 ```python43-http = httpcore.ConnectionPool([ssl], [timeout], [limits])44-response = await http.request(method, url, [headers], [body], [stream])48+>>> import httpcore49+>>>50+>>> client = httpcore.SyncClient()51+>>> response = client.get('http://example.com')52+>>> response.status_code53+<StatusCode.ok: 200>54+>>> response.text55+'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>\n...'56 ```57 47-ConnectionPool as a context-manager:58+---59 49-```python50-async with httpcore.ConnectionPool([ssl], [timeout], [limits]) as http:51- response = await http.request(method, url, [headers], [body], [stream])52-```60+## API Reference61 54-Streaming responses:62+#### `Client([ssl], [timeout], [pool_limits], [max_redirects])`63 56-```python57-http = httpcore.ConnectionPool()58-response = await http.request(method, url, stream=True)59-async for part in response.stream():60- ...61-```64+* `.request(method, url, ...)`65+* `.get(url, ...)`66+* `.options(url, ...)`67+* `.head(url, ...)`68+* `.post(url, ...)`69+* `.put(url, ...)`70+* `.patch(url, ...)`71+* `.delete(url, ...)`72+* `.prepare_request(request)`73+* `.send(request, ...)`74+* `.close()`75 63-Raw data without gzip/deflate/brotli decompression applied:76+### Models77 65-```python66-http = httpcore.ConnectionPool()67-response = await http.request(method, url, stream=True)68-async for part in response.raw():69- ...70-```78+#### `Response(...)`79 72-Thread-synchronous requests:80+* `.status_code` - **int**81+* `.reason_phrase` - **str**82+* `.protocol` - `"HTTP/2"` or `"HTTP/1.1"`83+* `.url` - **URL**84+* `.headers` - **Headers**85+* `.content` - **bytes**86+* `.text` - **str**87+* `.encoding` - **str**88+* `.json()` - **Any** *TODO*89+* `.read()` - **bytes**90+* `.stream()` - **bytes iterator**91+* `.raw()` - **bytes iterator**92+* `.close()` - **None**93+* `.is_redirect` - **bool**94+* `.request` - **Request**95+* `.cookies` - **Cookies** *TODO*96+* `.history` - **List[Response]**97+* `.raise_for_status()` - **Response** *TODO*98+* `.next()` - **Response**99 100+#### `Request(method, url, content, headers)`101+102+...103+104+#### `URL(url, allow_relative=False)`105+106+*A normalized, IDNA supporting URL.*107+108+* `.scheme` - **str**109+* `.authority` - **str**110+* `.host` - **str**111+* `.port` - **int**112+* `.path` - **str**113+* `.query` - **str**114+* `.full_path` - **str**115+* `.fragment` - **str**116+* `.is_ssl` - **bool**117+* `.origin` - **Origin**118+* `.is_absolute_url` - **bool**119+* `.is_relative_url` - **bool**120+* `.copy_with([scheme], [authority], [path], [query], [fragment])` - **URL**121+* `.resolve_with(url)` - **URL**122+123+#### `Origin(url)`124+125+*A normalized, IDNA supporting set of scheme/host/port info.*126+127 ```python75-http = httpcore.SyncConnectionPool()76-response = http.request('GET', 'http://example.com')77-assert response.status_code == 20078-assert response.body == b'Hello, world'128+>>> Origin('https://example.org') == Origin('HTTPS://EXAMPLE.ORG:443')129+True130 ```131 81-## Building a Gateway Server132+* `.is_ssl` - **bool**133+* `.host` - **str**134+* `.port` - **int**135 83-The level of abstraction fits in really well if you're just writing at84-the raw ASGI level. Eg. Here's an how an ASGI gateway server looks against the85-API, including streaming uploads and downloads...136+#### `Headers(headers)`137 138+*A case-insensitive multi-dict.*139+140 ```python88-import httpcore141+>>> headers = Headers({'Content-Type': 'application/json'})142+>>> headers['content-type']143+'application/json'144+```145 146+___147 91-class GatewayServer:92- def __init__(self, base_url):93- self.base_url = base_url94- self.http = httpcore.ConnectionPool()148+## Alternate backends149 96- async def __call__(self, scope, receive, send):97- assert scope['type'] == 'http'98- path = scope['path']99- query = scope['query_string']100- method = scope['method']101- headers = [102- (k, v) for (k, v) in scope['headers']103- if k not in (b'host', b'transfer-encoding')104- ]150+### `SyncClient`151 106- url = self.base_url + path107- if query:108- url += '?' + query.decode()152+A thread-synchronous client.153 110- initial_body, more_body = await self.initial_body(receive)111- if more_body:112- # Streaming request.113- body = self.stream_body(receive, initial_body)114- else:115- # Standard request.116- body = initial_body154+### `TrioClient`155 118- response = await self.http.request(119- method, url, headers=headers, body=body, stream=True120- )156+*TODO*157 122- await send({123- 'type': 'http.response.start',124- 'status': response.status_code,125- 'headers': response.headers126- })127- data = b''128- async for next_data in response.raw():129- if data:130- await send({131- 'type': 'http.response.body',132- 'body': data,133- 'more_body': True134- })135- data = next_data136- await send({'type': 'http.response.body', 'body': data})158+---159 138- async def initial_body(self, receive):139- """140- Pull the first body message off the 'receive' channel.141- Allows us to determine if we should use a streaming request or not.142- """143- message = await receive()144- body = message.get('body', b'')145- more_body = message.get('more_body', False)146- return (body, more_body)160+## The Stack161 148- async def stream_body(self, receive, initial_body):149- """150- Async iterator returning bytes for the request body.151- """152- yield initial_body153- while True:154- message = await receive()155- yield message.get('body', b'')156- if not message.get('more_body', False):157- break162+The `httpcore` client builds up behavior in a modular way.163 164+This makes it easier to dig into an understand the behaviour of any one aspect in isolation, as well as making it easier to test or to adapt for custom behaviors.165 160-app = GatewayServer('http://example.org')161-```166+You can also use lower level components in isolation if required, eg. Use a `ConnectionPool` without providing sessions, redirects etc...167 163-Run with...164-165-```shell166-uvicorn example:app167-```168+* `RedirectAdapter` - Adds redirect support.169+* `EnvironmentAdapter` - Adds `.netrc` and envvars such as `REQUESTS_CA_BUNDLE`.170+* `CookieAdapter` - Adds cookie persistence.171+* `AuthAdapter` - Adds authentication support.172+* `ConnectionPool` - Connection pooling & keep alive.173+ * `HTTPConnection` - A single connection.174+ * `HTTP11Connection` - A single HTTP/1.1 connection.175+ * `HTTP2Connection` - A single HTTP/2 connection, with multiple streams.