Skip to content

Commit 1497a42

Browse files
Documenting the network backend API (#699)
* Documenting the network backend API * Add example for working with a network backend directly * Network backend docs * Update docs/network-backends.md Co-authored-by: Florimond Manca <[email protected]> * Add 'httpcore.AnyIONetworkBackend' and 'httpcore.TrioNetworkBackend' to the API * Add networking backends to top-level API * httpcore.backends becomes private, since backends are available at documented top-level API now * Justify TrioBackend over AnyIOBackend * Rename '_backends/asyncio.py' to '_backends/anyio.py' * Use neater join for HTTP/1.1 example * Tweak example of working with stream directly * Minor docs tweaks, from working through * Minor docs tweaks, from working through * Minor test tweak * Link to network backends docs from 'network_stream' extension docs * Add Networking Backend line item to the CHANGELOG --------- Co-authored-by: Florimond Manca <[email protected]>
1 parent bfd235f commit 1497a42

37 files changed

+406
-51
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file.
44

55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
66

7+
## unreleased
8+
9+
- The networking backend interface has [been added to the public API](https://www.encode.io/httpcore/network-backends). Some classes which were previously private implementation detail are now part of the top-level public API. (#699)
10+
711
## 0.17.2 (May 23th, 2023)
812

913
- Add `socket_options` argument to `ConnectionPool` and `HTTProxy` classes. (#668)

docs/extensions.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,8 @@ The interface provided by the network stream:
200200

201201
This API can be used as the foundation for working with HTTP proxies, WebSocket upgrades, and other advanced use-cases.
202202

203+
See the [network backends documentation](network-backends.md) for more information on working directly with network streams.
204+
203205
##### `CONNECT` requests
204206

205207
A proxy CONNECT request using the network stream:

docs/network-backends.md

Lines changed: 277 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,279 @@
11
# Network Backends
22

3-
TODO
3+
The API layer at which `httpcore` interacts with the network is described as the network backend. Various backend implementations are provided, allowing `httpcore` to handle networking in different runtime contexts.
4+
5+
## Working with network backends
6+
7+
### The default network backend
8+
9+
Typically you won't need to specify a network backend, as a default will automatically be selected. However, understanding how the network backends fit in may be useful if you want to better understand the underlying architecture. Let's start by seeing how we can explicitly select the network backend.
10+
11+
First we're making a standard HTTP request, using a connection pool:
12+
13+
```python
14+
import httpcore
15+
16+
with httpcore.ConnectionPool() as http:
17+
response = http.request('GET', 'https://www.example.com')
18+
print(response)
19+
```
20+
21+
We can also have the same behavior, but be explicit with our selection of the network backend:
22+
23+
```python
24+
import httpcore
25+
26+
network_backend = httpcore.SyncBackend()
27+
with httpcore.ConnectionPool(network_backend=network_backend) as http:
28+
response = http.request('GET', 'https://www.example.com')
29+
print(response)
30+
```
31+
32+
The `httpcore.SyncBackend()` implementation handles the opening of TCP connections, and operations on the socket stream, such as reading, writing, and closing the connection.
33+
34+
We can get a better understanding of this by using a network backend to send a basic HTTP/1.1 request directly:
35+
36+
```python
37+
import httpcore
38+
39+
# Create an SSL context using 'certifi' for the certificates.
40+
ssl_context = httpcore.default_ssl_context()
41+
42+
# A basic HTTP/1.1 request as a plain bytestring.
43+
request = b'\r\n'.join([
44+
b'GET / HTTP/1.1',
45+
b'Host: www.example.com',
46+
b'Accept: */*',
47+
b'Connection: close',
48+
b''
49+
])
50+
51+
# Open a TCP stream and upgrade it to SSL.
52+
network_backend = httpcore.SyncBackend()
53+
network_stream = network_backend.connect_tcp("www.example.com", 443)
54+
network_stream = network_stream.start_tls(ssl_context, server_hostname="www.example.com")
55+
56+
# Send the HTTP request.
57+
network_stream.write(request)
58+
59+
# Read the HTTP response.
60+
while True:
61+
response = network_stream.read(max_bytes=4096)
62+
if response == b'':
63+
break
64+
print(response)
65+
66+
# The output should look something like this:
67+
#
68+
# b'HTTP/1.1 200 OK\r\nAge: 600005\r\n [...] Content-Length: 1256\r\nConnection: close\r\n\r\n'
69+
# b'<!doctype html>\n<html>\n<head>\n <title>Example Domain</title> [...] </html>\n'
70+
```
71+
72+
### Async network backends
73+
74+
If we're working with an `async` codebase, then we need to select a different backend.
75+
76+
The `httpcore.AnyIOBackend` is suitable for usage if you're running under `asyncio`. This is a networking backend implemented using [the `anyio` package](https://anyio.readthedocs.io/en/3.x/).
77+
78+
```python
79+
import httpcore
80+
import asyncio
81+
82+
async def main():
83+
network_backend = httpcore.AnyIOBackend()
84+
async with httpcore.AsyncConnectionPool(network_backend=network_backend) as http:
85+
response = await http.request('GET', 'https://www.example.com')
86+
print(response)
87+
88+
asyncio.run(main())
89+
```
90+
91+
The `AnyIOBackend` will work when running under either `asyncio` or `trio`. However, if you're working with async using the [`trio` framework](https://trio.readthedocs.io/en/stable/), then we recommend using the `httpcore.TrioBackend`.
92+
93+
This will give you the same kind of networking behavior you'd have using `AnyIOBackend`, but there will be a little less indirection so it will be marginally more efficient and will present cleaner tracebacks in error cases.
94+
95+
```python
96+
import httpcore
97+
import trio
98+
99+
async def main():
100+
network_backend = httpcore.TrioBackend()
101+
async with httpcore.AsyncConnectionPool(network_backend=network_backend) as http:
102+
response = await http.request('GET', 'https://www.example.com')
103+
print(response)
104+
105+
trio.run(main)
106+
```
107+
108+
### Mock network backends
109+
110+
There are also mock network backends available that can be useful for testing purposes.
111+
These backends accept a list of bytes, and return network stream interfaces that return those byte streams.
112+
113+
Here's an example of mocking a simple HTTP/1.1 response...
114+
115+
```python
116+
import httpcore
117+
118+
network_backend = httpcore.MockBackend([
119+
b"HTTP/1.1 200 OK\r\n",
120+
b"Content-Type: plain/text\r\n",
121+
b"Content-Length: 13\r\n",
122+
b"\r\n",
123+
b"Hello, world!",
124+
])
125+
with httpcore.ConnectionPool(network_backend=network_backend) as http:
126+
response = http.request("GET", "https://example.com/")
127+
print(response.extensions['http_version'])
128+
print(response.status)
129+
print(response.content)
130+
```
131+
132+
Mocking a HTTP/2 response is more complex, since it uses a binary format...
133+
134+
```python
135+
import hpack
136+
import hyperframe.frame
137+
import httpcore
138+
139+
content = [
140+
hyperframe.frame.SettingsFrame().serialize(),
141+
hyperframe.frame.HeadersFrame(
142+
stream_id=1,
143+
data=hpack.Encoder().encode(
144+
[
145+
(b":status", b"200"),
146+
(b"content-type", b"plain/text"),
147+
]
148+
),
149+
flags=["END_HEADERS"],
150+
).serialize(),
151+
hyperframe.frame.DataFrame(
152+
stream_id=1, data=b"Hello, world!", flags=["END_STREAM"]
153+
).serialize(),
154+
]
155+
# Note that we instantiate the mock backend with an `http2=True` argument.
156+
# This ensures that the mock network stream acts as if the `h2` ALPN flag has been set,
157+
# and causes the connection pool to interact with the connection using HTTP/2.
158+
network_backend = httpcore.MockBackend(content, http2=True)
159+
with httpcore.ConnectionPool(network_backend=network_backend) as http:
160+
response = http.request("GET", "https://example.com/")
161+
print(response.extensions['http_version'])
162+
print(response.status)
163+
print(response.content)
164+
```
165+
166+
### Custom network backends
167+
168+
The base interface for network backends is provided as public API, allowing you to implement custom networking behavior.
169+
170+
You can use this to provide advanced networking functionality such as:
171+
172+
* Network recording / replay.
173+
* In-depth debug tooling.
174+
* Handling non-standard SSL or DNS requirements.
175+
176+
Here's an example that records the network response to a file on disk:
177+
178+
```python
179+
import httpcore
180+
181+
182+
class RecordingNetworkStream(httpcore.NetworkStream):
183+
def __init__(self, record_file, stream):
184+
self.record_file = record_file
185+
self.stream = stream
186+
187+
def read(self, max_bytes, timeout=None):
188+
data = self.stream.read(max_bytes, timeout=timeout)
189+
self.record_file.write(data)
190+
return data
191+
192+
def write(self, buffer, timeout=None):
193+
self.stream.write(buffer, timeout=timeout)
194+
195+
def close(self) -> None:
196+
self.stream.close()
197+
198+
def start_tls(
199+
self,
200+
ssl_context,
201+
server_hostname=None,
202+
timeout=None,
203+
):
204+
self.stream = self.stream.start_tls(
205+
ssl_context, server_hostname=server_hostname, timeout=timeout
206+
)
207+
return self
208+
209+
def get_extra_info(self, info):
210+
return self.stream.get_extra_info(info)
211+
212+
213+
class RecordingNetworkBackend(httpcore.NetworkBackend):
214+
"""
215+
A custom network backend that records network responses.
216+
"""
217+
def __init__(self, record_file):
218+
self.record_file = record_file
219+
self.backend = httpcore.SyncBackend()
220+
221+
def connect_tcp(
222+
self,
223+
host,
224+
port,
225+
timeout=None,
226+
local_address=None,
227+
socket_options=None,
228+
):
229+
# Note that we're only using a single record file here,
230+
# so even if multiple connections are opened the network
231+
# traffic will all write to the same file.
232+
233+
# An alternative implementation might automatically use
234+
# a new file for each opened connection.
235+
stream = self.backend.connect_tcp(
236+
host,
237+
port,
238+
timeout=timeout,
239+
local_address=local_address,
240+
socket_options=socket_options
241+
)
242+
return RecordingNetworkStream(self.record_file, stream)
243+
244+
245+
# Once you make the request, the raw HTTP/1.1 response will be available
246+
# in the 'network-recording' file.
247+
#
248+
# Try switching to `http2=True` to see the difference when recording HTTP/2 binary network traffic,
249+
# or add `headers={'Accept-Encoding': 'gzip'}` to see HTTP content compression.
250+
with open("network-recording", "wb") as record_file:
251+
network_backend = RecordingNetworkBackend(record_file)
252+
with httpcore.ConnectionPool(network_backend=network_backend) as http:
253+
response = http.request("GET", "https://www.example.com/")
254+
print(response)
255+
```
256+
257+
---
258+
259+
## Reference
260+
261+
### Networking Backends
262+
263+
* `httpcore.SyncBackend`
264+
* `httpcore.AnyIOBackend`
265+
* `httpcore.TrioBackend`
266+
267+
### Mock Backends
268+
269+
* `httpcore.MockBackend`
270+
* `httpcore.MockStream`
271+
* `httpcore.AsyncMockBackend`
272+
* `httpcore.AsyncMockStream`
273+
274+
### Base Interface
275+
276+
* `httpcore.NetworkBackend`
277+
* `httpcore.NetworkStream`
278+
* `httpcore.AsyncNetworkBackend`
279+
* `httpcore.AsyncNetworkStream`

httpcore/__init__.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,15 @@
88
AsyncHTTPProxy,
99
AsyncSOCKSProxy,
1010
)
11+
from ._backends.base import (
12+
SOCKET_OPTION,
13+
AsyncNetworkBackend,
14+
AsyncNetworkStream,
15+
NetworkBackend,
16+
NetworkStream,
17+
)
18+
from ._backends.mock import AsyncMockBackend, AsyncMockStream, MockBackend, MockStream
19+
from ._backends.sync import SyncBackend
1120
from ._exceptions import (
1221
ConnectError,
1322
ConnectionNotAvailable,
@@ -37,6 +46,30 @@
3746
SOCKSProxy,
3847
)
3948

49+
# The 'httpcore.AnyIOBackend' class is conditional on 'anyio' being installed.
50+
try:
51+
from ._backends.anyio import AnyIOBackend
52+
except ImportError: # pragma: nocover
53+
54+
class AnyIOBackend: # type: ignore
55+
def __init__(self, *args, **kwargs): # type: ignore
56+
msg = (
57+
"Attempted to use 'httpcore.AnyIOBackend' but 'anyio' is not installed."
58+
)
59+
raise RuntimeError(msg)
60+
61+
62+
# The 'httpcore.TrioBackend' class is conditional on 'trio' being installed.
63+
try:
64+
from ._backends.trio import TrioBackend
65+
except ImportError: # pragma: nocover
66+
67+
class TrioBackend: # type: ignore
68+
def __init__(self, *args, **kwargs): # type: ignore
69+
msg = "Attempted to use 'httpcore.TrioBackend' but 'trio' is not installed."
70+
raise RuntimeError(msg)
71+
72+
4073
__all__ = [
4174
# top-level requests
4275
"request",
@@ -62,8 +95,23 @@
6295
"HTTP2Connection",
6396
"ConnectionInterface",
6497
"SOCKSProxy",
98+
# network backends, implementations
99+
"SyncBackend",
100+
"AnyIOBackend",
101+
"TrioBackend",
102+
# network backends, mock implementations
103+
"AsyncMockBackend",
104+
"AsyncMockStream",
105+
"MockBackend",
106+
"MockStream",
107+
# network backends, interface
108+
"AsyncNetworkStream",
109+
"AsyncNetworkBackend",
110+
"NetworkStream",
111+
"NetworkBackend",
65112
# util
66113
"default_ssl_context",
114+
"SOCKET_OPTION",
67115
# exceptions
68116
"ConnectionNotAvailable",
69117
"ProxyError",

httpcore/_async/connection.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@
44
from types import TracebackType
55
from typing import Iterable, Iterator, Optional, Type
66

7+
from .._backends.auto import AutoBackend
8+
from .._backends.base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream
79
from .._exceptions import ConnectError, ConnectionNotAvailable, ConnectTimeout
810
from .._models import Origin, Request, Response
911
from .._ssl import default_ssl_context
1012
from .._synchronization import AsyncLock
1113
from .._trace import Trace
12-
from ..backends.auto import AutoBackend
13-
from ..backends.base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream
1414
from .http11 import AsyncHTTP11Connection
1515
from .interfaces import AsyncConnectionInterface
1616

0 commit comments

Comments
 (0)