transports.md
This file
Path
docs/advanced/transports.md
344 lines · 10.6 KiB · Markdown
Last changed by
Fix sections references (#3058)Kar Petrosyanbefore adoption73e6888
History of this fileTake it
Docs restructuring. (#3049)Tom Christiebefore adoption8cd952c
lines 1–343why, 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.45## HTTPTransport67For 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.45* Mocking out external services during tests or in dev/staging environments.4647Here's an example of integrating against a Flask application:4849```python50from flask import Flask51import httpx525354app = Flask(__name__)5556@app.route("/")57def hello():58 return "Hello World!"5960with httpx.Client(app=app, base_url="http://testserver") as client:61 r = client.get("/")62 assert r.status_code == 20063 assert r.text == "Hello World!"64```6566For some more complex cases you might need to customize the WSGI transport. This allows you to:6768* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.69* Mount the WSGI application at a subpath by setting `script_name` (WSGI).70* Use a given client address for requests by setting `remote_addr` (WSGI).7172For example:7374```python75# Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4".76transport = httpx.WSGITransport(app=app, remote_addr="1.2.3.4")77with httpx.Client(transport=transport, base_url="http://testserver") as client:78 ...79```8081## urllib3 transport8283This [public gist](https://gist.github.com/florimondmanca/d56764d78d748eb9f73165da388e546e) provides a transport that uses the excellent [`urllib3` library](https://urllib3.readthedocs.io/en/latest/), and can be used with the sync `Client`...8485```pycon86>>> import httpx87>>> from urllib3_transport import URLLib3Transport88>>> client = httpx.Client(transport=URLLib3Transport())89>>> client.get("https://example.org")90<Response [200 OK]>91```9293## Custom transports9495A transport instance must implement the low-level Transport API, which deals96with sending a single request, and returning a response. You should either97subclass `httpx.BaseTransport` to implement a transport to use with `Client`,98or subclass `httpx.AsyncBaseTransport` to implement a transport to99use with `AsyncClient`.100101At the layer of the transport API we're using the familiar `Request` and102`Response` models.103104See the `handle_request` and `handle_async_request` docstrings for more details105on the specifics of the Transport API.106107A complete example of a custom transport implementation would be:108109```python110import json111import httpx112113114class HelloWorldTransport(httpx.BaseTransport):115 """116 A mock transport that always returns a JSON "Hello, world!" response.117 """118119 def handle_request(self, request):120 message = {"text": "Hello, world!"}121 content = json.dumps(message).encode("utf-8")122 stream = httpx.ByteStream(content)123 headers = [(b"content-type", b"application/json")]124 return httpx.Response(200, headers=headers, stream=stream)125```126127Which we can use in the same way:128129```pycon130>>> import httpx131>>> client = httpx.Client(transport=HelloWorldTransport())132>>> response = client.get("https://example.org/")133>>> response.json()134{"text": "Hello, world!"}135```136137## Mock transports138139During testing it can often be useful to be able to mock out a transport,140and return pre-determined responses, rather than making actual network requests.141142The `httpx.MockTransport` class accepts a handler function, which can be used143to map requests onto pre-determined responses:144145```python146def handler(request):147 return httpx.Response(200, json={"text": "Hello, world!"})148149150# Switch to a mock transport, if the TESTING environment variable is set.151if os.environ.get('TESTING', '').upper() == "TRUE":152 transport = httpx.MockTransport(handler)153else:154 transport = httpx.HTTPTransport()155156client = httpx.Client(transport=transport)157```158159For more advanced use-cases you might want to take a look at either [the third-party160mocking library, RESPX](https://lundberg.github.io/respx/), or the [pytest-httpx library](https://github.com/Colin-b/pytest_httpx).161162## Mounting transports163164You can also mount transports against given schemes or domains, to control165which transport an outgoing request should be routed via, with [the same style166used for specifying proxy routing](#routing).167168```python169import httpx170171class HTTPSRedirectTransport(httpx.BaseTransport):172 """173 A transport that always redirects to HTTPS.174 """175176 def handle_request(self, method, url, headers, stream, extensions):177 scheme, host, port, path = url178 if port is None:179 location = b"https://%s%s" % (host, path)180 else:181 location = b"https://%s:%d%s" % (host, port, path)182 stream = httpx.ByteStream(b"")183 headers = [(b"location", location)]184 extensions = {}185 return 303, headers, stream, extensions186187188# A client where any `http` requests are always redirected to `https`189mounts = {'http://': HTTPSRedirectTransport()}190client = httpx.Client(mounts=mounts)191```192193A couple of other sketches of how you might take advantage of mounted transports...194195Disabling HTTP/2 on a single given domain...196197```python198mounts = {199 "all://": httpx.HTTPTransport(http2=True),200 "all://*example.org": httpx.HTTPTransport()201}202client = httpx.Client(mounts=mounts)203```204205Mocking requests to a given domain:206207```python208# All requests to "example.org" should be mocked out.209# Other requests occur as usual.210def handler(request):211 return httpx.Response(200, json={"text": "Hello, World!"})212213mounts = {"all://example.org": httpx.MockTransport(handler)}214client = httpx.Client(mounts=mounts)215```216217Adding support for custom schemes:218219```python220# Support URLs like "file:///Users/sylvia_green/websites/new_client/index.html"221mounts = {"file://": FileSystemTransport()}222client = httpx.Client(mounts=mounts)223```224225### Routing226227HTTPX provides a powerful mechanism for routing requests, allowing you to write complex rules that specify which transport should be used for each request.228229The `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://`).230231HTTPX supports routing requests based on **scheme**, **domain**, **port**, or a combination of these.232233### Wildcard routing234235Route everything through a transport...236237```python238mounts = {239 "all://": httpx.HTTPTransport(proxy="http://localhost:8030"),240}241```242243### Scheme routing244245Route HTTP requests through one transport, and HTTPS requests through another...246247```python248mounts = {249 "http://": httpx.HTTPTransport(proxy="http://localhost:8030"),250 "https://": httpx.HTTPTransport(proxy="http://localhost:8031"),251}252```253254### Domain routing255256Proxy all requests on domain "example.com", let other requests pass through...257258```python259mounts = {260 "all://example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),261}262```263264Proxy HTTP requests on domain "example.com", let HTTPS and other requests pass through...265266```python267mounts = {268 "http://example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),269}270```271272Proxy all requests to "example.com" and its subdomains, let other requests pass through...273274```python275mounts = {276 "all://*example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),277}278```279280Proxy all requests to strict subdomains of "example.com", let "example.com" and other requests pass through...281282```python283mounts = {284 "all://*.example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),285}286```287288### Port routing289290Proxy HTTPS requests on port 1234 to "example.com"...291292```python293mounts = {294 "https://example.com:1234": httpx.HTTPTransport(proxy="http://localhost:8030"),295}296```297298Proxy all requests on port 1234...299300```python301mounts = {302 "all://*:1234": httpx.HTTPTransport(proxy="http://localhost:8030"),303}304```305306### No-proxy support307308It is also possible to define requests that _shouldn't_ be routed through the transport.309310To do so, pass `None` as the proxy URL. For example...311312```python313mounts = {314 # Route requests through a proxy by default...315 "all://": httpx.HTTPTransport(proxy="http://localhost:8031"),316 # Except those for "example.com".317 "all://example.com": None,318}319```320321### Complex configuration example322323You can combine the routing features outlined above to build complex proxy routing configurations. For example...324325```python326mounts = {327 # Route all traffic through a proxy by default...328 "all://": httpx.HTTPTransport(proxy="http://localhost:8030"),329 # But don't use proxies for HTTPS requests to "domain.io"...330 "https://domain.io": None,331 # And use another proxy for requests to "example.com" and its subdomains...332 "all://*example.com": httpx.HTTPTransport(proxy="http://localhost:8031"),333 # And yet another proxy if HTTP is used,334 # and the "internal" subdomain on port 5550 is requested...335 "http://internal.example.com:5550": httpx.HTTPTransport(proxy="http://localhost:8032"),336}337```338339### Environment variables340341There are also environment variables that can be used to control the dictionary of the client mounts. 342They can be used to configure HTTP proxying for clients.343Fix sections references (#3058)Kar Petrosyanbefore adoption73e6888
line 344why, one step back344See documentation on [`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`](../environment_variables.md#http_proxy-https_proxy-all_proxy) for more information.