Skip to content
Myr

advanced.md

This file

Path

docs/advanced.md

272 lines · 8.0 KiB · Markdown

Last changed by

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

History of this file

Take it

Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970

lines 1–8why, one step back
1# Advanced Usage
23## Client Instances45Using a Client instance to make requests will give you HTTP connection pooling,6will provide cookie persistence, and allows you to apply configuration across7all outgoing requests.8

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 9–10why, one step back
9!!! hint
10 A Client instance is equivalent to a Session instance in `requests`.

Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7

line 11why, one step back
11

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 12–15why, one step back
12### Usage
1314The recommended way to use a `Client` is as a context manager. This will ensure that connections are properly cleaned up when leaving the `with` block:15

Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970

line 16why, one step back
16```python

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 17–26why, one step back
17>>> with httpx.Client() as client:
18... r = client.get('https://example.com')19... 20>>> r21<Response [200 OK]>22```2324Alternatively, you can explicitly close the connection pool without block-usage using `.close()`:2526```python

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 27why, one step back
27>>> client = httpx.Client()

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 28–32why, one step back
28>>> try:
29... r = client.get('https://example.com')30... finally:31... client.close()32...

Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970

lines 33–36why, one step back
33>>> r
34<Response [200 OK]>35```36

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 37–38why, one step back
37Once you have a `Client`, you can use all the features documented in the [Quickstart](/quickstart) guide.
38

Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970

lines 39–40why, one step back
39## Calling into Python Web Apps
40

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 41why, one step back
41You can configure an `httpx` client to call directly into a Python web

Fix some grammar in Advanced docs (#461)thebigmunchbefore adoption3917866

line 42why, one step back
42application using either the WSGI or ASGI protocol.

Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970

lines 43–45why, one step back
43
44This is particularly useful for two main use-cases:45

Fix some grammar in Advanced docs (#461)thebigmunchbefore adoption3917866

lines 46–47why, one step back
46* Using `httpx` as a client inside test cases.
47* Mocking out external services during tests or in dev/staging environments.

Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970

lines 48–52why, one step back
48
49Here's an example of integrating against a Flask application:5051```python52from flask import Flask

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 53why, one step back
53import httpx

Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970

lines 54–61why, one step back
54
5556app = Flask(__name__)5758@app.route("/")59def hello():60 return "Hello World!"61

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 62–65why, one step back
62with httpx.Client(app=app) as client:
63 r = client.get('http://example/')64 assert r.status_code == 20065 assert r.text == "Hello World!"

Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970

line 66why, one step back
66```

Documented netrc support (#225)Can Sarıgölbefore adoption21939fd

line 67why, one step back
67

Fix some grammar in Advanced docs (#461)thebigmunchbefore adoption3917866

line 68why, one step back
68For some more complex cases you might need to customize the WSGI or ASGI

Drop `raise_app_exceptions` Client argument. (#238)Tom Christiebefore adoptionef9fc0f

lines 69–70why, one step back
69dispatch. This allows you to:
70

Fix some grammar in Advanced docs (#461)thebigmunchbefore adoption3917866

lines 71–73why, one step back
71* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.
72* Mount the WSGI or ASGI application at a subpath by setting `script_name` (WSGI) or `root_path` (ASGI).73* Use a given client address for requests by setting `remote_addr` (WSGI) or `client` (ASGI).

Drop `raise_app_exceptions` Client argument. (#238)Tom Christiebefore adoptionef9fc0f

lines 74–78why, one step back
74
75For example:7677```python78# Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4".

Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b

line 79why, one step back
79dispatch = httpx.dispatch.WSGIDispatch(app=app, remote_addr="1.2.3.4")

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 80–81why, one step back
80with httpx.Client(dispatch=dispatch) as client:
81 ...

Drop `raise_app_exceptions` Client argument. (#238)Tom Christiebefore adoptionef9fc0f

lines 82–83why, one step back
82```
83

Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac

lines 84–89why, one step back
84## Build Request
8586You can use `Client.build_request()` to build a request and87make modifications before sending the request.8889```python

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 90–95why, one step back
90>>> with httpx.Client() as client:
91... req = client.build_request("OPTIONS", "https://example.com")92... req.url.full_path = "*" # Build an 'OPTIONS *' request for CORS93... r = client.send(req)94...95>>> r

Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac

lines 96–98why, one step back
96<Response [200 OK]>
97```98

Fix typos, spelling issues, and grammar in docs (#426)Kyle Galbraithbefore adoptionb65bce5

line 99why, one step back
99## Specify the version of the HTTP protocol

Add example of specifying HTTP versions (#337)Paul (xobb) Chubatyybefore adoption0c4460e

line 100why, one step back
100

Fix typos, spelling issues, and grammar in docs (#426)Kyle Galbraithbefore adoptionb65bce5

line 101why, one step back
101One can set the version of the HTTP protocol for the client in case you want to make the requests using a specific version.

Add example of specifying HTTP versions (#337)Paul (xobb) Chubatyybefore adoption0c4460e

lines 102–105why, one step back
102
103For example:104105```python

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 106–107why, one step back
106with httpx.Client(http_versions=["HTTP/1.1"]) as h11_client:
107 h11_response = h11_client.get("https://myserver.com")

Add example of specifying HTTP versions (#337)Paul (xobb) Chubatyybefore adoption0c4460e

line 108why, one step back
108

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 109–110why, one step back
109with httpx.Client(http_versions=["HTTP/2"]) as h2_client:
110 h2_response = h2_client.get("https://myserver.com")

Add example of specifying HTTP versions (#337)Paul (xobb) Chubatyybefore adoption0c4460e

lines 111–112why, one step back
111```
112

Documented netrc support (#225)Can Sarıgölbefore adoption21939fd

lines 113–117why, one step back
113## .netrc Support
114115HTTPX supports .netrc file. In `trust_env=True` cases, if auth parameter is116not defined, HTTPX tries to add auth into request's header from .netrc file.117

Cache netrc authentication per-client (#400)Can Sarıgölbefore adoption84731c8

lines 118–122why, one step back
118!!! note
119 The NETRC file is cached across requests made by a client.120 If you need to refresh the cache (e.g. because the NETRC file has changed),121 you should create a new client or restart the interpreter.122

Documented netrc support (#225)Can Sarıgölbefore adoption21939fd

lines 123–144why, one step back
123As default `trust_env` is true. To set false:
124```python125>>> httpx.get('https://example.org/', trust_env=False)126```127128If `NETRC` environment is empty, HTTPX tries to use default files.129(`~/.netrc`, `~/_netrc`)130131To change `NETRC` environment:132```python133>>> import os134>>> os.environ["NETRC"] = "my_default_folder/.my_netrc"135```136137.netrc file content example:138```139machine netrcexample.org140login example-username141password example-password142143...144```

Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085

lines 145–152why, one step back
145
146## HTTP Proxying147148HTTPX supports setting up proxies the same way that Requests does via the `proxies` parameter.149For example to forward all HTTP traffic to `http://127.0.0.1:3080` and all HTTPS traffic150to `http://127.0.0.1:3081` your `proxies` config would look like this:151152```python

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 153–158why, one step back
153>>> proxies = {
154... "http": "http://127.0.0.1:3080",155... "https": "http://127.0.0.1:3081"156... }157>>> with httpx.Client(proxies=proxies) as client:158... ...

Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085

lines 159–165why, one step back
159```
160161Proxies can be configured for a specific scheme and host, all schemes of a host,162all hosts for a scheme, or for all requests. When determining which proxy configuration163to use for a given request this same order is used.164165```python

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 166–177why, one step back
166>>> proxies = {
167... "http://example.com": "...", # Host+Scheme168... "all://example.com": "...", # Host169... "http": "...", # Scheme170... "all": "...", # All171... }172>>> with httpx.Client(proxies=proxies) as client:173... ...174... 175>>> proxy = "..." # Shortcut for {'all': '...'}176>>> with httpx.Client(proxies=proxy) as client:177... ...

Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085

lines 178–195why, one step back
178```
179180!!! warning181 To make sure that proxies cannot read your traffic,182 and even if the proxy_url uses HTTPS, it is recommended to183 use HTTPS and tunnel requests if possible.184185By default `HTTPProxy` will operate as a forwarding proxy for `http://...` requests186and will establish a `CONNECT` TCP tunnel for `https://` requests. This doesn't change187regardless of the `proxy_url` being `http` or `https`.188189Proxies can be configured to have different behavior such as forwarding or tunneling all requests:190191```python192proxy = httpx.HTTPProxy(193 proxy_url="https://127.0.0.1",194 proxy_mode=httpx.HTTPProxyMode.TUNNEL_ONLY195)

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 196–198why, one step back
196with httpx.Client(proxies=proxy) as client:
197 # This request will be tunneled instead of forwarded.198 r = client.get("http://example.com")

Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085

line 199why, one step back
199```

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

lines 200–222why, one step back
200
201202## Timeout fine-tuning203HTTPX offers various request timeout management options. Three types of timeouts are available: **connect** timeouts, 204**write** timeouts and **read** timeouts.205206* The **connect timeout** specifies the maximum amount of time to wait until a connection to the requested host is established. 207If HTTPX is unable to connect within this time frame, a `ConnectTimeout` exception is raised.208* The **write timeout** specifies the maximum duration to wait for a chunk of data to be sent (for example, a chunk of the request body). 209If HTTPX is unable to send data within this time frame, a `WriteTimeout` exception is raised.210* The **read timeout** specifies the maximum duration to wait for a chunk of data to be received (for example, a chunk of the response body). 211If HTTPX is unable to receive data within this time frame, a `ReadTimeout` exception is raised.212213### Setting timeouts214You can set timeouts on two levels:215216- For a given request:217218```python219# Using top-level API220httpx.get('http://example.com/api/v1/example', timeout=5)221222# Or, with a client:

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 223–224why, one step back
223with httpx.Client() as client:
224 client.get("http://example.com/api/v1/example", timeout=5)

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

lines 225–229why, one step back
225```
226227- On a client instance, which results in the given `timeout` being used as a default for requests made with this client:228229```python

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 230–231why, one step back
230with httpx.Client(timeout=5) as client:
231 client.get('http://example.com/api/v1/example')

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

lines 232–261why, one step back
232```
233234Besides, you can pass timeouts in two forms:235236- A number, which sets the read, write and connect timeouts to the same value, as in the examples above. 237- A `TimeoutConfig` instance, which allows to define the read, write and connect timeouts independently:238239```python240timeout = httpx.TimeoutConfig(241 connect_timeout=5, 242 read_timeout=10, 243 write_timeout=15244)245246resp = httpx.get('http://example.com/api/v1/example', timeout=timeout)247```248249### Default timeouts250By default all types of timeouts are set to 5 second.251 252### Disabling timeouts253To disable timeouts, you can pass `None` as a timeout parameter. 254Note that currently this is not supported by the top-level API.255256```python257url = "http://example.com/api/v1/delay/10"258259httpx.get(url, timeout=None) # Times out after 5s260261

Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25

lines 262–263why, one step back
262with httpx.Client(timeout=None) as client:
263 client.get(url) # Does not timeout, returns after 10s

Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499

lines 264–272why, one step back
264
265266timeout = httpx.TimeoutConfig(267 connect_timeout=5, 268 read_timeout=None, 269 write_timeout=5270)271httpx.get(url, timeout=timeout) # Does not timeout, returns after 10s272```