transports.md
This file
Path
docs/advanced/transports.md
454 lines · 13.9 KiB · Markdown
Last changed by
Improve 'Custom transports' docs (#3081)Tom Christiebefore adoption3faa4a8
History of this fileTake it
Docs restructuring. (#3049)Tom Christiebefore adoption8cd952c
lines 1–4why, one step back1HTTPX'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.4Improve 'Custom transports' docs (#3081)Tom Christiebefore adoption3faa4a8
line 5why, one step back5## HTTP TransportDocs restructuring. (#3049)Tom Christiebefore adoption8cd952c
lines 6–44why, one step back67For 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.1011```pycon12>>> import httpx13>>> transport = httpx.HTTPTransport(local_address="0.0.0.0")14>>> client = httpx.Client(transport=transport)15```1617Connection retries are also available via this interface. Requests will be retried the given number of times in case an `httpx.ConnectError` or an `httpx.ConnectTimeout` occurs, allowing smoother operation under flaky networks. If you need other forms of retry behaviors, such as handling read/write errors or reacting to `503 Service Unavailable`, consider general-purpose tools such as [tenacity](https://github.com/jd/tenacity).1819```pycon20>>> import httpx21>>> transport = httpx.HTTPTransport(retries=1)22>>> client = httpx.Client(transport=transport)23```2425Similarly, instantiating a transport directly provides a `uds` option for26connecting via a Unix Domain Socket that is only available via this low-level API:2728```pycon29>>> import httpx30>>> # Connect to the Docker API via a Unix Socket.31>>> transport = httpx.HTTPTransport(uds="/var/run/docker.sock")32>>> client = httpx.Client(transport=transport)33>>> response = client.get("http://docker/info")34>>> response.json()35{"ID": "...", "Containers": 4, "Images": 74, ...}36```3738## WSGI Transport3940You can configure an `httpx` client to call directly into a Python web application using the WSGI protocol.4142This is particularly useful for two main use-cases:4344* Using `httpx` as a client inside test cases.Deprecate `app=...` in favor of explicit `WSGITransport`/`ASGITransport`. (#3050)Tom Christiebefore adoptioncabd1c0
line 45why, one step back45* Mocking out external services during tests or in dev or staging environments.Docs restructuring. (#3049)Tom Christiebefore adoption8cd952c
line 46why, one step back46Deprecate `app=...` in favor of explicit `WSGITransport`/`ASGITransport`. (#3050)Tom Christiebefore adoptioncabd1c0
lines 47–48why, one step back47### Example48Docs restructuring. (#3049)Tom Christiebefore adoption8cd952c
lines 49–61why, one step back49Here's an example of integrating against a Flask application:5051```python52from flask import Flask53import httpx545556app = Flask(__name__)5758@app.route("/")59def hello():60 return "Hello World!"61Deprecate `app=...` in favor of explicit `WSGITransport`/`ASGITransport`. (#3050)Tom Christiebefore adoptioncabd1c0
lines 62–63why, one step back62transport = httpx.WSGITransport(app=app)63with httpx.Client(transport=transport, base_url="http://testserver") as client:Docs restructuring. (#3049)Tom Christiebefore adoption8cd952c
lines 64–68why, one step back64 r = client.get("/")65 assert r.status_code == 20066 assert r.text == "Hello World!"67```68Deprecate `app=...` in favor of explicit `WSGITransport`/`ASGITransport`. (#3050)Tom Christiebefore adoptioncabd1c0
lines 69–70why, one step back69### Configuration70Docs restructuring. (#3049)Tom Christiebefore adoption8cd952c
lines 71–84why, one step back71For some more complex cases you might need to customize the WSGI transport. This allows you to:7273* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.74* Mount the WSGI application at a subpath by setting `script_name` (WSGI).75* Use a given client address for requests by setting `remote_addr` (WSGI).7677For example:7879```python80# Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4".81transport = httpx.WSGITransport(app=app, remote_addr="1.2.3.4")82with httpx.Client(transport=transport, base_url="http://testserver") as client:83 ...84```Deprecate `app=...` in favor of explicit `WSGITransport`/`ASGITransport`. (#3050)Tom Christiebefore adoptioncabd1c0
line 85why, one step back85Improve 'Custom transports' docs (#3081)Tom Christiebefore adoption3faa4a8
line 86why, one step back86## ASGI TransportDeprecate `app=...` in favor of explicit `WSGITransport`/`ASGITransport`. (#3050)Tom Christiebefore adoptioncabd1c0
lines 87–147why, one step back8788You 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:9192* Using `httpx` as a client inside test cases.93* Mocking out external services during tests or in dev or staging environments.9495### Example9697Let's take this Starlette application as an example:9899```python100from starlette.applications import Starlette101from starlette.responses import HTMLResponse102from starlette.routing import Route103104105async def hello(request):106 return HTMLResponse("Hello World!")107108109app = Starlette(routes=[Route("/", hello)])110```111112We can make requests directly against the application, like so:113114```python115transport = httpx.ASGITransport(app=app)116117async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:118 r = await client.get("/")119 assert r.status_code == 200120 assert r.text == "Hello World!"121```122123### Configuration124125For some more complex cases you might need to customise the ASGI transport. This allows you to:126127* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.128* Mount the ASGI application at a subpath by setting `root_path`.129* Use a given client address for requests by setting `client`.130131For example:132133```python134# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",135# on port 123.136transport = httpx.ASGITransport(app=app, client=("1.2.3.4", 123))137async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:138 ...139```140141See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path` keys.142143### ASGI startup and shutdown144145It is not in the scope of HTTPX to trigger ASGI lifespan events of your app.146147However it is suggested to use `LifespanManager` from [asgi-lifespan](https://github.com/florimondmanca/asgi-lifespan#usage) in pair with `AsyncClient`.Docs restructuring. (#3049)Tom Christiebefore adoption8cd952c
lines 148–150why, one step back148149## Custom transports150Improve 'Custom transports' docs (#3081)Tom Christiebefore adoption3faa4a8
line 151why, one step back151A transport instance must implement the low-level Transport API which dealsDocs restructuring. (#3049)Tom Christiebefore adoption8cd952c
lines 152–174why, one step back152with 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`.156157At the layer of the transport API we're using the familiar `Request` and158`Response` models.159160See the `handle_request` and `handle_async_request` docstrings for more details161on the specifics of the Transport API.162163A complete example of a custom transport implementation would be:164165```python166import json167import httpx168169class HelloWorldTransport(httpx.BaseTransport):170 """171 A mock transport that always returns a JSON "Hello, world!" response.172 """173174 def handle_request(self, request):Improve 'Custom transports' docs (#3081)Tom Christiebefore adoption3faa4a8
line 175why, one step back175 return httpx.Response(200, json={"text": "Hello, world!"})Docs restructuring. (#3049)Tom Christiebefore adoption8cd952c
lines 176–177why, one step back176```177Improve 'Custom transports' docs (#3081)Tom Christiebefore adoption3faa4a8
line 178why, one step back178Or this example, which uses a custom transport and `httpx.Mounts` to always redirect `http://` requests.Docs restructuring. (#3049)Tom Christiebefore adoption8cd952c
line 179why, one step back179Improve 'Custom transports' docs (#3081)Tom Christiebefore adoption3faa4a8
lines 180–243why, one step back180```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)Docs restructuring. (#3049)Tom Christiebefore adoption8cd952c
lines 244–452why, one step back244```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.250251The `httpx.MockTransport` class accepts a handler function, which can be used252to map requests onto pre-determined responses:253254```python255def handler(request):256 return httpx.Response(200, json={"text": "Hello, world!"})257258259# Switch to a mock transport, if the TESTING environment variable is set.260if os.environ.get('TESTING', '').upper() == "TRUE":261 transport = httpx.MockTransport(handler)262else:263 transport = httpx.HTTPTransport()264265client = httpx.Client(transport=transport)266```267268For more advanced use-cases you might want to take a look at either [the third-party269mocking library, RESPX](https://lundberg.github.io/respx/), or the [pytest-httpx library](https://github.com/Colin-b/pytest_httpx).270271## Mounting transports272273You can also mount transports against given schemes or domains, to control274which transport an outgoing request should be routed via, with [the same style275used for specifying proxy routing](#routing).276277```python278import httpx279280class HTTPSRedirectTransport(httpx.BaseTransport):281 """282 A transport that always redirects to HTTPS.283 """284285 def handle_request(self, method, url, headers, stream, extensions):286 scheme, host, port, path = url287 if port is None:288 location = b"https://%s%s" % (host, path)289 else:290 location = b"https://%s:%d%s" % (host, port, path)291 stream = httpx.ByteStream(b"")292 headers = [(b"location", location)]293 extensions = {}294 return 303, headers, stream, extensions295296297# A client where any `http` requests are always redirected to `https`298mounts = {'http://': HTTPSRedirectTransport()}299client = httpx.Client(mounts=mounts)300```301302A couple of other sketches of how you might take advantage of mounted transports...303304Disabling HTTP/2 on a single given domain...305306```python307mounts = {308 "all://": httpx.HTTPTransport(http2=True),309 "all://*example.org": httpx.HTTPTransport()310}311client = httpx.Client(mounts=mounts)312```313314Mocking requests to a given domain:315316```python317# All requests to "example.org" should be mocked out.318# Other requests occur as usual.319def handler(request):320 return httpx.Response(200, json={"text": "Hello, World!"})321322mounts = {"all://example.org": httpx.MockTransport(handler)}323client = httpx.Client(mounts=mounts)324```325326Adding support for custom schemes:327328```python329# Support URLs like "file:///Users/sylvia_green/websites/new_client/index.html"330mounts = {"file://": FileSystemTransport()}331client = httpx.Client(mounts=mounts)332```333334### Routing335336HTTPX provides a powerful mechanism for routing requests, allowing you to write complex rules that specify which transport should be used for each request.337338The `mounts` dictionary maps URL patterns to HTTP transports. HTTPX matches requested URLs against URL patterns to decide which transport should be used, if any. Matching is done from most specific URL patterns (e.g. `https://<domain>:<port>`) to least specific ones (e.g. `https://`).339340HTTPX supports routing requests based on **scheme**, **domain**, **port**, or a combination of these.341342### Wildcard routing343344Route everything through a transport...345346```python347mounts = {348 "all://": httpx.HTTPTransport(proxy="http://localhost:8030"),349}350```351352### Scheme routing353354Route HTTP requests through one transport, and HTTPS requests through another...355356```python357mounts = {358 "http://": httpx.HTTPTransport(proxy="http://localhost:8030"),359 "https://": httpx.HTTPTransport(proxy="http://localhost:8031"),360}361```362363### Domain routing364365Proxy all requests on domain "example.com", let other requests pass through...366367```python368mounts = {369 "all://example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),370}371```372373Proxy HTTP requests on domain "example.com", let HTTPS and other requests pass through...374375```python376mounts = {377 "http://example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),378}379```380381Proxy all requests to "example.com" and its subdomains, let other requests pass through...382383```python384mounts = {385 "all://*example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),386}387```388389Proxy all requests to strict subdomains of "example.com", let "example.com" and other requests pass through...390391```python392mounts = {393 "all://*.example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),394}395```396397### Port routing398399Proxy HTTPS requests on port 1234 to "example.com"...400401```python402mounts = {403 "https://example.com:1234": httpx.HTTPTransport(proxy="http://localhost:8030"),404}405```406407Proxy all requests on port 1234...408409```python410mounts = {411 "all://*:1234": httpx.HTTPTransport(proxy="http://localhost:8030"),412}413```414415### No-proxy support416417It is also possible to define requests that _shouldn't_ be routed through the transport.418419To do so, pass `None` as the proxy URL. For example...420421```python422mounts = {423 # Route requests through a proxy by default...424 "all://": httpx.HTTPTransport(proxy="http://localhost:8031"),425 # Except those for "example.com".426 "all://example.com": None,427}428```429430### Complex configuration example431432You can combine the routing features outlined above to build complex proxy routing configurations. For example...433434```python435mounts = {436 # Route all traffic through a proxy by default...437 "all://": httpx.HTTPTransport(proxy="http://localhost:8030"),438 # But don't use proxies for HTTPS requests to "domain.io"...439 "https://domain.io": None,440 # And use another proxy for requests to "example.com" and its subdomains...441 "all://*example.com": httpx.HTTPTransport(proxy="http://localhost:8031"),442 # And yet another proxy if HTTP is used,443 # and the "internal" subdomain on port 5550 is requested...444 "http://internal.example.com:5550": httpx.HTTPTransport(proxy="http://localhost:8032"),445}446```447448### Environment variables449450There are also environment variables that can be used to control the dictionary of the client mounts. 451They can be used to configure HTTP proxying for clients.452Mention NO_PROXY environment variable on Advanced Usage page (#3066)Richie B2Bbefore adoption37a2901
lines 453–454why, one step back453See documentation on [`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`](../environment_variables.md#http_proxy-https_proxy-all_proxy)454and [`NO_PROXY`](../environment_variables.md#no_proxy) for more information.