advanced.md
This file
Path
docs/advanced.md
313 lines · 9.4 KiB · Markdown
Last changed by
Document client-level configuration (#488)Florimond Mancabefore adoptionad38db8
History of this fileTake it
Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970
lines 1–8why, one step back1# Advanced Usage23## 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.8Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 9–10why, one step back9!!! hint10 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 back11Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 12–15why, one step back12### Usage1314The 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:15Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970
line 16why, one step back16```pythonDocument client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 17–26why, one step back17>>> 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```pythonRenaming -> httpx (#129)Tom Christiebefore adoption2d09d5b
line 27why, one step back27>>> client = httpx.Client()Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 28–32why, one step back28>>> 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 back33>>> r34<Response [200 OK]>35```36Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 37–38why, one step back37Once you have a `Client`, you can use all the features documented in the [Quickstart](/quickstart) guide.38Document client-level configuration (#488)Florimond Mancabefore adoptionad38db8
lines 39–74why, one step back39### Configuration4041Clients allow you to apply configuration to all outgoing requests by passing parameters to the `Client` constructor.4243For example, to apply a set of custom headers on every request:4445```python46>>> url = 'http://httpbin.org/headers'47>>> headers = {'user-agent': 'my-app/0.0.1'}48>>> with httpx.Client(headers=headers) as client:49... r = client.get(url)50...51>>> r.json()['headers']['User-Agent']52'my-app/0.0.1'53```5455!!! note56 When you provide a parameter at both the client and request levels, one of two things can happen:57 58 - For headers, query parameters and cookies, the values are merged into one.59 - For all other parameters, the request-level value is used.6061Additionally, `Client` constructor accepts some parameters that aren't available at the request level.6263One particularly useful parameter is `base_url`, which allows you to define a base URL to prepend to all outgoing requests:6465```python66>>> with httpx.Client(base_url='http://httpbin.org') as client:67... r = client.get('/headers')68... 69>>> r.request.url70URL('http://httpbin.org/headers')71```7273For a list of all available client-level parameters, see the [`Client` API reference](/api/#client).74Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970
lines 75–76why, one step back75## Calling into Python Web Apps76Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b
line 77why, one step back77You can configure an `httpx` client to call directly into a Python webFix some grammar in Advanced docs (#461)thebigmunchbefore adoption3917866
line 78why, one step back78application using either the WSGI or ASGI protocol.Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970
lines 79–81why, one step back7980This is particularly useful for two main use-cases:81Fix some grammar in Advanced docs (#461)thebigmunchbefore adoption3917866
lines 82–83why, one step back82* Using `httpx` as a client inside test cases.83* Mocking out external services during tests or in dev/staging environments.Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970
lines 84–88why, one step back8485Here's an example of integrating against a Flask application:8687```python88from flask import FlaskRenaming -> httpx (#129)Tom Christiebefore adoption2d09d5b
line 89why, one step back89import httpxSupport WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970
lines 90–97why, one step back909192app = Flask(__name__)9394@app.route("/")95def hello():96 return "Hello World!"97Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 98–101why, one step back98with httpx.Client(app=app) as client:99 r = client.get('http://example/')100 assert r.status_code == 200101 assert r.text == "Hello World!"Support WSGI and ASGI apps. (#94)Tom Christiebefore adoptionbb86970
line 102why, one step back102```Documented netrc support (#225)Can Sarıgölbefore adoption21939fd
line 103why, one step back103Fix some grammar in Advanced docs (#461)thebigmunchbefore adoption3917866
line 104why, one step back104For some more complex cases you might need to customize the WSGI or ASGIDrop `raise_app_exceptions` Client argument. (#238)Tom Christiebefore adoptionef9fc0f
lines 105–106why, one step back105dispatch. This allows you to:106Fix some grammar in Advanced docs (#461)thebigmunchbefore adoption3917866
lines 107–109why, one step back107* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.108* Mount the WSGI or ASGI application at a subpath by setting `script_name` (WSGI) or `root_path` (ASGI).109* 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 110–114why, one step back110111For example:112113```python114# 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 115why, one step back115dispatch = httpx.dispatch.WSGIDispatch(app=app, remote_addr="1.2.3.4")Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 116–117why, one step back116with httpx.Client(dispatch=dispatch) as client:117 ...Drop `raise_app_exceptions` Client argument. (#238)Tom Christiebefore adoptionef9fc0f
lines 118–119why, one step back118```119Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac
lines 120–125why, one step back120## Build Request121122You can use `Client.build_request()` to build a request and123make modifications before sending the request.124125```pythonDocument client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 126–131why, one step back126>>> with httpx.Client() as client:127... req = client.build_request("OPTIONS", "https://example.com")128... req.url.full_path = "*" # Build an 'OPTIONS *' request for CORS129... r = client.send(req)130...131>>> rAdd `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac
lines 132–134why, one step back132<Response [200 OK]>133```134Fix typos, spelling issues, and grammar in docs (#426)Kyle Galbraithbefore adoptionb65bce5
line 135why, one step back135## Specify the version of the HTTP protocolAdd example of specifying HTTP versions (#337)Paul (xobb) Chubatyybefore adoption0c4460e
line 136why, one step back136Fix typos, spelling issues, and grammar in docs (#426)Kyle Galbraithbefore adoptionb65bce5
line 137why, one step back137One 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 138–141why, one step back138139For example:140141```pythonDocument client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 142–143why, one step back142with httpx.Client(http_versions=["HTTP/1.1"]) as h11_client:143 h11_response = h11_client.get("https://myserver.com")Add example of specifying HTTP versions (#337)Paul (xobb) Chubatyybefore adoption0c4460e
line 144why, one step back144Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 145–146why, one step back145with httpx.Client(http_versions=["HTTP/2"]) as h2_client:146 h2_response = h2_client.get("https://myserver.com")Add example of specifying HTTP versions (#337)Paul (xobb) Chubatyybefore adoption0c4460e
lines 147–148why, one step back147```148Documented netrc support (#225)Can Sarıgölbefore adoption21939fd
lines 149–153why, one step back149## .netrc Support150151HTTPX supports .netrc file. In `trust_env=True` cases, if auth parameter is152not defined, HTTPX tries to add auth into request's header from .netrc file.153Cache netrc authentication per-client (#400)Can Sarıgölbefore adoption84731c8
lines 154–158why, one step back154!!! note155 The NETRC file is cached across requests made by a client.156 If you need to refresh the cache (e.g. because the NETRC file has changed),157 you should create a new client or restart the interpreter.158Documented netrc support (#225)Can Sarıgölbefore adoption21939fd
lines 159–180why, one step back159As default `trust_env` is true. To set false:160```python161>>> httpx.get('https://example.org/', trust_env=False)162```163164If `NETRC` environment is empty, HTTPX tries to use default files.165(`~/.netrc`, `~/_netrc`)166167To change `NETRC` environment:168```python169>>> import os170>>> os.environ["NETRC"] = "my_default_folder/.my_netrc"171```172173.netrc file content example:174```175machine netrcexample.org176login example-username177password example-password178179...180```Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085
lines 181–188why, one step back181182## HTTP Proxying183184HTTPX supports setting up proxies the same way that Requests does via the `proxies` parameter.185For example to forward all HTTP traffic to `http://127.0.0.1:3080` and all HTTPS traffic186to `http://127.0.0.1:3081` your `proxies` config would look like this:187188```pythonDocument client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 189–194why, one step back189>>> proxies = {190... "http": "http://127.0.0.1:3080",191... "https": "http://127.0.0.1:3081"192... }193>>> with httpx.Client(proxies=proxies) as client:194... ...Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085
lines 195–201why, one step back195```196197Proxies can be configured for a specific scheme and host, all schemes of a host,198all hosts for a scheme, or for all requests. When determining which proxy configuration199to use for a given request this same order is used.200201```pythonDocument client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 202–213why, one step back202>>> proxies = {203... "http://example.com": "...", # Host+Scheme204... "all://example.com": "...", # Host205... "http": "...", # Scheme206... "all": "...", # All207... }208>>> with httpx.Client(proxies=proxies) as client:209... ...210... 211>>> proxy = "..." # Shortcut for {'all': '...'}212>>> with httpx.Client(proxies=proxy) as client:213... ...Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085
lines 214–231why, one step back214```215216!!! warning217 To make sure that proxies cannot read your traffic,218 and even if the proxy_url uses HTTPS, it is recommended to219 use HTTPS and tunnel requests if possible.220221By default `HTTPProxy` will operate as a forwarding proxy for `http://...` requests222and will establish a `CONNECT` TCP tunnel for `https://` requests. This doesn't change223regardless of the `proxy_url` being `http` or `https`.224225Proxies can be configured to have different behavior such as forwarding or tunneling all requests:226227```python228proxy = httpx.HTTPProxy(229 proxy_url="https://127.0.0.1",230 proxy_mode=httpx.HTTPProxyMode.TUNNEL_ONLY231)Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 232–234why, one step back232with httpx.Client(proxies=proxy) as client:233 # This request will be tunneled instead of forwarded.234 r = client.get("http://example.com")Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085
line 235why, one step back235```Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 236why, one step back236Drop proxies parameter from the high level API (#485)Yeray Diaz Diazbefore adoption09db6ec
lines 237–241why, one step back237!!! note238239 Per request proxy configuration, i.e. `client.get(url, proxies=...)`,240 has not been implemented yet. To use proxies you must pass the proxy241 information at `Client` initialization.Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 242–263why, one step back242243## Timeout fine-tuning244HTTPX offers various request timeout management options. Three types of timeouts are available: **connect** timeouts, 245**write** timeouts and **read** timeouts.246247* The **connect timeout** specifies the maximum amount of time to wait until a connection to the requested host is established. 248If HTTPX is unable to connect within this time frame, a `ConnectTimeout` exception is raised.249* 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). 250If HTTPX is unable to send data within this time frame, a `WriteTimeout` exception is raised.251* 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). 252If HTTPX is unable to receive data within this time frame, a `ReadTimeout` exception is raised.253254### Setting timeouts255You can set timeouts on two levels:256257- For a given request:258259```python260# Using top-level API261httpx.get('http://example.com/api/v1/example', timeout=5)262263# Or, with a client:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 264–265why, one step back264with httpx.Client() as client:265 client.get("http://example.com/api/v1/example", timeout=5)Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 266–270why, one step back266```267268- On a client instance, which results in the given `timeout` being used as a default for requests made with this client:269270```pythonDocument client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 271–272why, one step back271with httpx.Client(timeout=5) as client:272 client.get('http://example.com/api/v1/example')Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 273–302why, one step back273```274275Besides, you can pass timeouts in two forms:276277- A number, which sets the read, write and connect timeouts to the same value, as in the examples above. 278- A `TimeoutConfig` instance, which allows to define the read, write and connect timeouts independently:279280```python281timeout = httpx.TimeoutConfig(282 connect_timeout=5, 283 read_timeout=10, 284 write_timeout=15285)286287resp = httpx.get('http://example.com/api/v1/example', timeout=timeout)288```289290### Default timeouts291By default all types of timeouts are set to 5 second.292 293### Disabling timeouts294To disable timeouts, you can pass `None` as a timeout parameter. 295Note that currently this is not supported by the top-level API.296297```python298url = "http://example.com/api/v1/delay/10"299300httpx.get(url, timeout=None) # Times out after 5s301302Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 303–304why, one step back303with httpx.Client(timeout=None) as client:304 client.get(url) # Does not timeout, returns after 10sAdd timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 305–313why, one step back305306307timeout = httpx.TimeoutConfig(308 connect_timeout=5, 309 read_timeout=None, 310 write_timeout=5311)312httpx.get(url, timeout=timeout) # Does not timeout, returns after 10s313```