Skip to content
Myr

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

1 file+69 added−16 removed

modified:docs/advanced/transports.md+69 added-16 removed
1HTTPX's `Client` also accepts a `transport` argument. This argument allows you2to provide a custom Transport object that will be used to perform the actual3sending of the requests.45## HTTPTransport5## HTTP Transport67For some advanced configuration you might need to instantiate a transport8class 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 lines
82with httpx.Client(transport=transport, base_url="http://testserver") as client:83 ...84```8586## ASGITransport86## ASGI Transport8788You can configure an `httpx` client to call directly into an async Python web application using the ASGI protocol.8990This is particularly useful for two main use-cases:
56 unmodified lines
147However it is suggested to use `LifespanManager` from [asgi-lifespan](https://github.com/florimondmanca/asgi-lifespan#usage) in pair with `AsyncClient`.148149## Custom transports150151A transport instance must implement the low-level Transport API, which deals151A transport instance must implement the low-level Transport API which deals152with sending a single request, and returning a response. You should either153subclass `httpx.BaseTransport` to implement a transport to use with `Client`,154or subclass `httpx.AsyncBaseTransport` to implement a transport to155use with `AsyncClient`.
9 unmodified lines
165```python166import json167import httpx168169169class HelloWorldTransport(httpx.BaseTransport):170 """171 A mock transport that always returns a JSON "Hello, world!" response.172 """173174 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```177183Which we can use in the same way:178Or this example, which uses a custom transport and `httpx.Mounts` to always redirect `http://` requests.179185```pycon186>>> import httpx187>>> client = httpx.Client(transport=HelloWorldTransport())188>>> response = client.get("https://example.org/")189>>> response.json()190{"text": "Hello, world!"}180```python181class 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)})188189# A client where any `http` requests are always redirected to `https`190transport = httpx.Mounts({191 'http://': HTTPSRedirect()192 'https://': httpx.HTTPTransport()193})194client = httpx.Client(transport=transport)195```196197A useful pattern here is custom transport classes that wrap the default HTTP implementation. For example...198199```python200class DebuggingTransport(httpx.BaseTransport):201 def __init__(self, **kwargs):202 self._wrapper = httpx.HTTPTransport(**kwargs)203204 def handle_request(self, request):205 print(f">>> {request}")206 response = self._wrapper.handle_request(request)207 print(f"<<< {response}")208 return response209210 def close(self):211 self._wrapper.close()212213transport = DebuggingTransport()214client = httpx.Client(transport=transport)215```216217Here's another case, where we're using a round-robin across a number of different proxies...218219```python220class 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 = 0227228 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)232233 def close(self):234 for transport in self._transports:235 transport.close()236237proxies = [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]242transport = ProxyRoundRobin(proxies=proxies)243client = httpx.Client(transport=transport)244```245246## Mock transports247248During testing it can often be useful to be able to mock out a transport,249and return pre-determined responses, rather than making actual network requests.
205 unmodified lines