Debian Codegraph @

docs/advanced/transports.md

raw
1 HTTPX's `Client` also accepts a `transport` argument. This argument allows you
2 to provide a custom Transport object that will be used to perform the actual
3 sending of the requests.
4
5 ## HTTP Transport
6
7 For some advanced configuration you might need to instantiate a transport
8 class directly, and pass it to the client instance. One example is the
9 `local_address` configuration which is only available via this low-level API.
10
11 ```pycon
12 >>> import httpx
13 >>> transport = httpx.HTTPTransport(local_address="0.0.0.0")
14 >>> client = httpx.Client(transport=transport)
15 ```
16
17 Connection 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).
18
19 ```pycon
20 >>> import httpx
21 >>> transport = httpx.HTTPTransport(retries=1)
22 >>> client = httpx.Client(transport=transport)
23 ```
24
25 Similarly, instantiating a transport directly provides a `uds` option for
26 connecting via a Unix Domain Socket that is only available via this low-level API:
27
28 ```pycon
29 >>> import httpx
30 >>> # 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 ```
37
38 ## WSGI Transport
39
40 You can configure an `httpx` client to call directly into a Python web application using the WSGI protocol.
41
42 This is particularly useful for two main use-cases:
43
44 * Using `httpx` as a client inside test cases.
45 * Mocking out external services during tests or in dev or staging environments.
46
47 ### Example
48
49 Here's an example of integrating against a Flask application:
50
51 ```python
52 from flask import Flask
53 import httpx
54
55
56 app = Flask(__name__)
57
58 @app.route("/")
59 def hello():
60 return "Hello World!"
61
62 transport = httpx.WSGITransport(app=app)
63 with httpx.Client(transport=transport, base_url="http://testserver") as client:
64 r = client.get("/")
65 assert r.status_code == 200
66 assert r.text == "Hello World!"
67 ```
68
69 ### Configuration
70
71 For some more complex cases you might need to customize the WSGI transport. This allows you to:
72
73 * 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).
76
77 For example:
78
79 ```python
80 # Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4".
81 transport = httpx.WSGITransport(app=app, remote_addr="1.2.3.4")
82 with httpx.Client(transport=transport, base_url="http://testserver") as client:
83 ...
84 ```
85
86 ## ASGI Transport
87
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:
91
92 * Using `httpx` as a client inside test cases.
93 * Mocking out external services during tests or in dev or staging environments.
94
95 ### Example
96
97 Let's take this Starlette application as an example:
98
99 ```python
100 from starlette.applications import Starlette
101 from starlette.responses import HTMLResponse
102 from starlette.routing import Route
103
104
105 async def hello(request):
106 return HTMLResponse("Hello World!")
107
108
109 app = Starlette(routes=[Route("/", hello)])
110 ```
111
112 We can make requests directly against the application, like so:
113
114 ```python
115 transport = httpx.ASGITransport(app=app)
116
117 async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
118 r = await client.get("/")
119 assert r.status_code == 200
120 assert r.text == "Hello World!"
121 ```
122
123 ### Configuration
124
125 For some more complex cases you might need to customise the ASGI transport. This allows you to:
126
127 * 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`.
130
131 For example:
132
133 ```python
134 # Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",
135 # on port 123.
136 transport = httpx.ASGITransport(app=app, client=("1.2.3.4", 123))
137 async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
138 ...
139 ```
140
141 See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path` keys.
142
143 ### ASGI startup and shutdown
144
145 It is not in the scope of HTTPX to trigger ASGI lifespan events of your app.
146
147 However it is suggested to use `LifespanManager` from [asgi-lifespan](https://github.com/florimondmanca/asgi-lifespan#usage) in pair with `AsyncClient`.
148
149 ## Custom transports
150
151 A transport instance must implement the low-level Transport API which deals
152 with sending a single request, and returning a response. You should either
153 subclass `httpx.BaseTransport` to implement a transport to use with `Client`,
154 or subclass `httpx.AsyncBaseTransport` to implement a transport to
155 use with `AsyncClient`.
156
157 At the layer of the transport API we're using the familiar `Request` and
158 `Response` models.
159
160 See the `handle_request` and `handle_async_request` docstrings for more details
161 on the specifics of the Transport API.
162
163 A complete example of a custom transport implementation would be:
164
165 ```python
166 import json
167 import httpx
168
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):
175 return httpx.Response(200, json={"text": "Hello, world!"})
176 ```
177
178 Or this example, which uses a custom transport and `httpx.Mounts` to always redirect `http://` requests.
179
180 ```python
181 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 ```python
200 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 response
209
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 ```python
220 class ProxyRoundRobin(httpx.BaseTransport):
221 def __init__(self, proxies, **kwargs):
222 self._transports = [
223 httpx.HTTPTransport(proxy=proxy, **kwargs)
224 for proxy in proxies
225 ]
226 self._idx = 0
227
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 transports
247
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.
250
251 The `httpx.MockTransport` class accepts a handler function, which can be used
252 to map requests onto pre-determined responses:
253
254 ```python
255 def handler(request):
256 return httpx.Response(200, json={"text": "Hello, world!"})
257
258
259 # Switch to a mock transport, if the TESTING environment variable is set.
260 if os.environ.get('TESTING', '').upper() == "TRUE":
261 transport = httpx.MockTransport(handler)
262 else:
263 transport = httpx.HTTPTransport()
264
265 client = httpx.Client(transport=transport)
266 ```
267
268 For more advanced use-cases you might want to take a look at either [the third-party
269 mocking library, RESPX](https://lundberg.github.io/respx/), or the [pytest-httpx library](https://github.com/Colin-b/pytest_httpx).
270
271 ## Mounting transports
272
273 You can also mount transports against given schemes or domains, to control
274 which transport an outgoing request should be routed via, with [the same style
275 used for specifying proxy routing](#routing).
276
277 ```python
278 import httpx
279
280 class HTTPSRedirectTransport(httpx.BaseTransport):
281 """
282 A transport that always redirects to HTTPS.
283 """
284
285 def handle_request(self, method, url, headers, stream, extensions):
286 scheme, host, port, path = url
287 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, extensions
295
296
297 # A client where any `http` requests are always redirected to `https`
298 mounts = {'http://': HTTPSRedirectTransport()}
299 client = httpx.Client(mounts=mounts)
300 ```
301
302 A couple of other sketches of how you might take advantage of mounted transports...
303
304 Disabling HTTP/2 on a single given domain...
305
306 ```python
307 mounts = {
308 "all://": httpx.HTTPTransport(http2=True),
309 "all://*example.org": httpx.HTTPTransport()
310 }
311 client = httpx.Client(mounts=mounts)
312 ```
313
314 Mocking requests to a given domain:
315
316 ```python
317 # All requests to "example.org" should be mocked out.
318 # Other requests occur as usual.
319 def handler(request):
320 return httpx.Response(200, json={"text": "Hello, World!"})
321
322 mounts = {"all://example.org": httpx.MockTransport(handler)}
323 client = httpx.Client(mounts=mounts)
324 ```
325
326 Adding support for custom schemes:
327
328 ```python
329 # Support URLs like "file:///Users/sylvia_green/websites/new_client/index.html"
330 mounts = {"file://": FileSystemTransport()}
331 client = httpx.Client(mounts=mounts)
332 ```
333
334 ### Routing
335
336 HTTPX provides a powerful mechanism for routing requests, allowing you to write complex rules that specify which transport should be used for each request.
337
338 The `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://`).
339
340 HTTPX supports routing requests based on **scheme**, **domain**, **port**, or a combination of these.
341
342 ### Wildcard routing
343
344 Route everything through a transport...
345
346 ```python
347 mounts = {
348 "all://": httpx.HTTPTransport(proxy="http://localhost:8030"),
349 }
350 ```
351
352 ### Scheme routing
353
354 Route HTTP requests through one transport, and HTTPS requests through another...
355
356 ```python
357 mounts = {
358 "http://": httpx.HTTPTransport(proxy="http://localhost:8030"),
359 "https://": httpx.HTTPTransport(proxy="http://localhost:8031"),
360 }
361 ```
362
363 ### Domain routing
364
365 Proxy all requests on domain "example.com", let other requests pass through...
366
367 ```python
368 mounts = {
369 "all://example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),
370 }
371 ```
372
373 Proxy HTTP requests on domain "example.com", let HTTPS and other requests pass through...
374
375 ```python
376 mounts = {
377 "http://example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),
378 }
379 ```
380
381 Proxy all requests to "example.com" and its subdomains, let other requests pass through...
382
383 ```python
384 mounts = {
385 "all://*example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),
386 }
387 ```
388
389 Proxy all requests to strict subdomains of "example.com", let "example.com" and other requests pass through...
390
391 ```python
392 mounts = {
393 "all://*.example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),
394 }
395 ```
396
397 ### Port routing
398
399 Proxy HTTPS requests on port 1234 to "example.com"...
400
401 ```python
402 mounts = {
403 "https://example.com:1234": httpx.HTTPTransport(proxy="http://localhost:8030"),
404 }
405 ```
406
407 Proxy all requests on port 1234...
408
409 ```python
410 mounts = {
411 "all://*:1234": httpx.HTTPTransport(proxy="http://localhost:8030"),
412 }
413 ```
414
415 ### No-proxy support
416
417 It is also possible to define requests that _shouldn't_ be routed through the transport.
418
419 To do so, pass `None` as the proxy URL. For example...
420
421 ```python
422 mounts = {
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 ```
429
430 ### Complex configuration example
431
432 You can combine the routing features outlined above to build complex proxy routing configurations. For example...
433
434 ```python
435 mounts = {
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 ```
447
448 ### Environment variables
449
450 There are also environment variables that can be used to control the dictionary of the client mounts.
451 They can be used to configure HTTP proxying for clients.
452
453 See documentation on [`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`](../environment_variables.md#http_proxy-https_proxy-all_proxy)
454 and [`NO_PROXY`](../environment_variables.md#no_proxy) for more information.