Skip to content
Myr

Document client block-usage and close() (#487)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Document client context manager vs close() usage * Convert client snippets to use context-managed syntax

authored by Florimond Manca · committed by GitHub · parent 7200717 · Browse files · 5 files+86 added−55 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+86 added−55 removed

  • other:+86 added−55 removed

5 files+86 added−55 removed

modified:docs/advanced.md+67 added-37 removed
4 unmodified lines
5Using 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.89!!! hint9A Client instance is equivalent to a Session instance in `requests`.10 A Client instance is equivalent to a Session instance in `requests`.1112### 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:1516```python17>>> 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```python27>>> client = httpx.Client()13>>> r = client.get('https://example.org/')28>>> try:29... r = client.get('https://example.com')30... finally:31... client.close()32... 33>>> r34<Response [200 OK]>35```3637Once you have a `Client`, you can use all the features documented in the [Quickstart](/quickstart) guide.3839## Calling into Python Web Apps4041You can configure an `httpx` client to call directly into a Python web42application using either the WSGI or ASGI protocol.
15 unmodified lines
58@app.route("/")59def hello():60 return "Hello World!"6141client = httpx.Client(app=app)42r = client.get('http://example/')43assert r.status_code == 20044assert r.text == "Hello World!"62with httpx.Client(app=app) as client:63 r = client.get('http://example/')64 assert r.status_code == 20065 assert r.text == "Hello World!"66```6768For some more complex cases you might need to customize the WSGI or ASGI69dispatch. This allows you to:
6 unmodified lines
7677```python78# Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4".79dispatch = httpx.dispatch.WSGIDispatch(app=app, remote_addr="1.2.3.4")59client = httpx.Client(dispatch=dispatch)80with httpx.Client(dispatch=dispatch) as client:81 ...82```8384## Build Request8586You can use `Client.build_request()` to build a request and87make modifications before sending the request.8889```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)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>>> r96<Response [200 OK]>97```9899## Specify the version of the HTTP protocol
2 unmodified lines
102103For example:104105```python82h11_client = httpx.Client(http_versions=["HTTP/1.1"])83h11_response = h11_client.get("https://myserver.com")106with httpx.Client(http_versions=["HTTP/1.1"]) as h11_client:107 h11_response = h11_client.get("https://myserver.com")10885h2_client = httpx.Client(http_versions=["HTTP/2"])86h2_response = h2_client.get("https://myserver.com")109with httpx.Client(http_versions=["HTTP/2"]) as h2_client:110 h2_response = h2_client.get("https://myserver.com")111```112113## .netrc Support114
34 unmodified lines
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```python129>>> client = httpx.Client(proxies={130 "http": "http://127.0.0.1:3080",131 "https": "http://127.0.0.1:3081"132})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... ...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```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'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... ...178```179180!!! warning181 To make sure that proxies cannot read your traffic,
10 unmodified lines
192proxy = httpx.HTTPProxy(193 proxy_url="https://127.0.0.1",194 proxy_mode=httpx.HTTPProxyMode.TUNNEL_ONLY195)165client = httpx.Client(proxies=proxy)166167# This request will be tunneled instead of forwarded.168client.get("http://example.com")196with httpx.Client(proxies=proxy) as client:197 # This request will be tunneled instead of forwarded.198 r = client.get("http://example.com")199```200201202## Timeout fine-tuning
16 unmodified lines
219# Using top-level API220httpx.get('http://example.com/api/v1/example', timeout=5)221222# Or, with a client:193client = httpx.Client()194client.get("http://example.com/api/v1/example", timeout=5)223with httpx.Client() as client:224 client.get("http://example.com/api/v1/example", timeout=5)225```226227- On a client instance, which results in the given `timeout` being used as a default for requests made with this client:228229```python200client = httpx.Client(timeout=5)201client.get('http://example.com/api/v1/example')230with httpx.Client(timeout=5) as client:231 client.get('http://example.com/api/v1/example')232```233234Besides, you can pass timeouts in two forms:235
22 unmodified lines
258259httpx.get(url, timeout=None) # Times out after 5s260261232client = httpx.Client(timeout=None)233client.get(url) # Does not timeout, returns after 10s262with httpx.Client(timeout=None) as client:263 client.get(url) # Does not timeout, returns after 10s264265266timeout = httpx.TimeoutConfig(267 connect_timeout=5, 268 read_timeout=None, 269 write_timeout=5270)271httpx.get(url, timeout=timeout) # Does not timeout, returns after 10s242```272```
modified:docs/api.md+2 added-2 removed
modified:docs/compatibility.md+2 added-1 removed
modified:docs/environment_variables.md+6 added-6 removed
24 unmodified lines
25Example:2627```python28# test_script.py2929import httpx31client = httpx.Client()32client.get("https://google.com")3031with httpx.Client() as client:32 r = client.get("https://google.com")33```3435```console36user@host:~$ HTTPX_DEBUG=1 python test_script.py
26 unmodified lines
63Example:6465```python66# test_script.py6767import httpx69client = httpx.Client()70client.get("https://google.com")6869with httpx.Client() as client:70 r = client.get("https://google.com")71```7273```console74SSLKEYLOGFILE=test.log python test_script.py
57 unmodified lines
modified:docs/parallel.md+9 added-9 removed
46 unmodified lines
47control the authentication or dispatch behavior for all requests within the48block.4950```python51>>> client = httpx.Client()52>>> with client.parallel() as parallel:53>>> ...51>>> with httpx.Client() as client:52... with client.parallel() as parallel:53... ...54```5556## Async parallel requests5758If you're working within an async framework, then you'll want to use a fully59async API for making requests.6061```python62>>> client = httpx.AsyncClient()63>>> async with client.parallel() as parallel:64>>> pending_one = await parallel.get('https://example.com/1')65>>> pending_two = await parallel.get('https://example.com/2')66>>> response_one = await pending_one.get_response()67>>> response_two = await pending_two.get_response()62>>> async with httpx.AsyncClient() as client:63... async with client.parallel() as parallel:64... pending_one = await parallel.get('https://example.com/1')65... pending_two = await parallel.get('https://example.com/2')66... response_one = await pending_one.get_response()67... response_two = await pending_two.get_response()68```6970See [the Async Client documentation](async.md) for more details.