Improve 'Custom transports' docs (#3081)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by GitHub · parent c51af4b · Browse files · 1 file·+69 added−16 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+69 added−16 removed
- other:+69 added−16 removed
Provenance
- Commit
3faa4a8- Tree
c29b80a- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
c51af4b
1 file changed+69 added−16 removed
modified:docs/advanced/transports.md+69 added-16 removed
1 HTTPX's `Client` also accepts a `transport` argument. This argument allows you2 to provide a custom Transport object that will be used to perform the actual3 sending of the requests.4 5-## HTTPTransport5+## HTTP Transport6 7 For some advanced configuration you might need to instantiate a transport8 class directly, and pass it to the client instance. One example is the9 `local_address` configuration which is only available via this low-level API.72 unmodified lines82 with httpx.Client(transport=transport, base_url="http://testserver") as client:83 ...84 ```85 86-## ASGITransport86+## ASGI Transport87 88 You can configure an `httpx` client to call directly into an async Python web application using the ASGI protocol.89 90 This is particularly useful for two main use-cases:56 unmodified lines147 However it is suggested to use `LifespanManager` from [asgi-lifespan](https://github.com/florimondmanca/asgi-lifespan#usage) in pair with `AsyncClient`.148 149 ## Custom transports150 151-A transport instance must implement the low-level Transport API, which deals151+A transport instance must implement the low-level Transport API which deals152 with sending a single request, and returning a response. You should either153 subclass `httpx.BaseTransport` to implement a transport to use with `Client`,154 or subclass `httpx.AsyncBaseTransport` to implement a transport to155 use with `AsyncClient`.9 unmodified lines165 ```python166 import json167 import httpx168 169-169 class HelloWorldTransport(httpx.BaseTransport):170 """171 A mock transport that always returns a JSON "Hello, world!" response.172 """173 174 def handle_request(self, request):176- message = {"text": "Hello, world!"}177- content = json.dumps(message).encode("utf-8")178- stream = httpx.ByteStream(content)179- headers = [(b"content-type", b"application/json")]180- return httpx.Response(200, headers=headers, stream=stream)175+ return httpx.Response(200, json={"text": "Hello, world!"})176 ```177 183-Which we can use in the same way:178+Or this example, which uses a custom transport and `httpx.Mounts` to always redirect `http://` requests.179 185-```pycon186->>> import httpx187->>> client = httpx.Client(transport=HelloWorldTransport())188->>> response = client.get("https://example.org/")189->>> response.json()190-{"text": "Hello, world!"}180+```python181+class HTTPSRedirect(httpx.BaseTransport):182+ """183+ A transport that always redirects to HTTPS.184+ """185+ def handle_request(self, request):186+ url = request.url.copy_with(scheme="https")187+ return httpx.Response(303, headers={"Location": str(url)})188+189+# A client where any `http` requests are always redirected to `https`190+transport = httpx.Mounts({191+ 'http://': HTTPSRedirect()192+ 'https://': httpx.HTTPTransport()193+})194+client = httpx.Client(transport=transport)195 ```196 197+A useful pattern here is custom transport classes that wrap the default HTTP implementation. For example...198+199+```python200+class DebuggingTransport(httpx.BaseTransport):201+ def __init__(self, **kwargs):202+ self._wrapper = httpx.HTTPTransport(**kwargs)203+204+ def handle_request(self, request):205+ print(f">>> {request}")206+ response = self._wrapper.handle_request(request)207+ print(f"<<< {response}")208+ return response209+210+ def close(self):211+ self._wrapper.close()212+213+transport = DebuggingTransport()214+client = httpx.Client(transport=transport)215+```216+217+Here's another case, where we're using a round-robin across a number of different proxies...218+219+```python220+class ProxyRoundRobin(httpx.BaseTransport):221+ def __init__(self, proxies, **kwargs):222+ self._transports = [223+ httpx.HTTPTransport(proxy=proxy, **kwargs)224+ for proxy in proxies225+ ]226+ self._idx = 0227+228+ def handle_request(self, request):229+ transport = self._transports[self._idx]230+ self._idx = (self._idx + 1) % len(self._transports)231+ return transport.handle_request(request)232+233+ def close(self):234+ for transport in self._transports:235+ transport.close()236+237+proxies = [238+ httpx.Proxy("http://127.0.0.1:8081"),239+ httpx.Proxy("http://127.0.0.1:8082"),240+ httpx.Proxy("http://127.0.0.1:8083"),241+]242+transport = ProxyRoundRobin(proxies=proxies)243+client = httpx.Client(transport=transport)244+```245+246 ## Mock transports247 248 During testing it can often be useful to be able to mock out a transport,249 and return pre-determined responses, rather than making actual network requests.205 unmodified lines