Skip to content
Myr

advanced.md

This file

Path

docs/advanced.md

242 lines · 7.2 KiB · Markdown

Last changed by

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

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

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

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

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

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

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

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

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

lines 13–19why, one step back
13>>> r = client.get('https://example.org/')
14>>> r15<Response [200 OK]>16```1718## Calling into Python Web Apps19

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

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

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

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

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

lines 22–24why, one step back
22
23This is particularly useful for two main use-cases:24

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

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

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

lines 27–31why, one step back
27
28Here's an example of integrating against a Flask application:2930```python31from flask import Flask

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 32why, one step back
32import httpx

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

lines 33–40why, one step back
33
3435app = Flask(__name__)3637@app.route("/")38def hello():39 return "Hello World!"40

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 41why, one step back
41client = httpx.Client(app=app)

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

lines 42–45why, one step back
42r = client.get('http://example/')
43assert r.status_code == 20044assert r.text == "Hello World!"45```

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

line 46why, one step back
46

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

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

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

lines 48–49why, one step back
48dispatch. This allows you to:
49

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

lines 50–52why, one step back
50* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.
51* Mount the WSGI or ASGI application at a subpath by setting `script_name` (WSGI) or `root_path` (ASGI).52* 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 53–57why, one step back
53
54For example:5556```python57# 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 58why, one step back
58dispatch = httpx.dispatch.WSGIDispatch(app=app, remote_addr="1.2.3.4")

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

lines 59–61why, one step back
59client = httpx.Client(dispatch=dispatch)
60```61

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

lines 62–74why, one step back
62## Build Request
6364You can use `Client.build_request()` to build a request and65make modifications before sending the request.6667```python68>>> client = httpx.Client()69>>> req = client.build_request("OPTIONS", "https://example.com")70>>> req.url.full_path = "*" # Build an 'OPTIONS *' request for CORS71>>> client.send(r)72<Response [200 OK]>73```74

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

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

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

line 76why, one step back
76

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

line 77why, one step back
77One 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 78–88why, one step back
78
79For example:8081```python82h11_client = httpx.Client(http_versions=["HTTP/1.1"])83h11_response = h11_client.get("https://myserver.com")8485h2_client = httpx.Client(http_versions=["HTTP/2"])86h2_response = h2_client.get("https://myserver.com")87```88

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

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

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

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

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

lines 99–120why, one step back
99As default `trust_env` is true. To set false:
100```python101>>> httpx.get('https://example.org/', trust_env=False)102```103104If `NETRC` environment is empty, HTTPX tries to use default files.105(`~/.netrc`, `~/_netrc`)106107To change `NETRC` environment:108```python109>>> import os110>>> os.environ["NETRC"] = "my_default_folder/.my_netrc"111```112113.netrc file content example:114```115machine netrcexample.org116login example-username117password example-password118119...120```

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

lines 121–166why, one step back
121
122## HTTP Proxying123124HTTPX supports setting up proxies the same way that Requests does via the `proxies` parameter.125For example to forward all HTTP traffic to `http://127.0.0.1:3080` and all HTTPS traffic126to `http://127.0.0.1:3081` your `proxies` config would look like this:127128```python129>>> client = httpx.Client(proxies={130 "http": "http://127.0.0.1:3080",131 "https": "http://127.0.0.1:3081"132})133```134135Proxies can be configured for a specific scheme and host, all schemes of a host,136all hosts for a scheme, or for all requests. When determining which proxy configuration137to use for a given request this same order is used.138139```python140>>> client = httpx.Client(proxies={141 "http://example.com": "...", # Host+Scheme142 "all://example.com": "...", # Host143 "http": "...", # Scheme144 "all": "...", # All145})146>>> client = httpx.Client(proxies="...") # Shortcut for 'all'147```148149!!! warning150 To make sure that proxies cannot read your traffic,151 and even if the proxy_url uses HTTPS, it is recommended to152 use HTTPS and tunnel requests if possible.153154By default `HTTPProxy` will operate as a forwarding proxy for `http://...` requests155and will establish a `CONNECT` TCP tunnel for `https://` requests. This doesn't change156regardless of the `proxy_url` being `http` or `https`.157158Proxies can be configured to have different behavior such as forwarding or tunneling all requests:159160```python161proxy = httpx.HTTPProxy(162 proxy_url="https://127.0.0.1",163 proxy_mode=httpx.HTTPProxyMode.TUNNEL_ONLY164)165client = httpx.Client(proxies=proxy)166

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

line 167why, one step back
167# This request will be tunneled instead of forwarded.

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

lines 168–169why, one step back
168client.get("http://example.com")
169```

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

lines 170–242why, one step back
170
171172## Timeout fine-tuning173HTTPX offers various request timeout management options. Three types of timeouts are available: **connect** timeouts, 174**write** timeouts and **read** timeouts.175176* The **connect timeout** specifies the maximum amount of time to wait until a connection to the requested host is established. 177If HTTPX is unable to connect within this time frame, a `ConnectTimeout` exception is raised.178* 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). 179If HTTPX is unable to send data within this time frame, a `WriteTimeout` exception is raised.180* 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). 181If HTTPX is unable to receive data within this time frame, a `ReadTimeout` exception is raised.182183### Setting timeouts184You can set timeouts on two levels:185186- For a given request:187188```python189# Using top-level API190httpx.get('http://example.com/api/v1/example', timeout=5)191192# Or, with a client:193client = httpx.Client()194client.get("http://example.com/api/v1/example", timeout=5)195```196197- On a client instance, which results in the given `timeout` being used as a default for requests made with this client:198199```python200client = httpx.Client(timeout=5)201client.get('http://example.com/api/v1/example')202```203204Besides, you can pass timeouts in two forms:205206- A number, which sets the read, write and connect timeouts to the same value, as in the examples above. 207- A `TimeoutConfig` instance, which allows to define the read, write and connect timeouts independently:208209```python210timeout = httpx.TimeoutConfig(211 connect_timeout=5, 212 read_timeout=10, 213 write_timeout=15214)215216resp = httpx.get('http://example.com/api/v1/example', timeout=timeout)217```218219### Default timeouts220By default all types of timeouts are set to 5 second.221 222### Disabling timeouts223To disable timeouts, you can pass `None` as a timeout parameter. 224Note that currently this is not supported by the top-level API.225226```python227url = "http://example.com/api/v1/delay/10"228229httpx.get(url, timeout=None) # Times out after 5s230231232client = httpx.Client(timeout=None)233client.get(url) # Does not timeout, returns after 10s234235236timeout = httpx.TimeoutConfig(237 connect_timeout=5, 238 read_timeout=None, 239 write_timeout=5240)241httpx.get(url, timeout=timeout) # Does not timeout, returns after 10s242```