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
Provenance
- Commit
074cd25- Tree
929e688- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
7200717
5 files changed+86 added−55 removed
modified:docs/advanced.md+67 added-37 removed
4 unmodified lines5 Using a Client instance to make requests will give you HTTP connection pooling,6 will provide cookie persistence, and allows you to apply configuration across7 all outgoing requests.8 9+!!! hint9-A Client instance is equivalent to a Session instance in `requests`.10+ A Client instance is equivalent to a Session instance in `requests`.11 12+### Usage13+14+The 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+16 ```python17+>>> with httpx.Client() as client:18+... r = client.get('https://example.com')19+... 20+>>> r21+<Response [200 OK]>22+```23+24+Alternatively, you can explicitly close the connection pool without block-usage using `.close()`:25+26+```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 ```36 37+Once you have a `Client`, you can use all the features documented in the [Quickstart](/quickstart) guide.38+39 ## Calling into Python Web Apps40 41 You can configure an `httpx` client to call directly into a Python web42 application using either the WSGI or ASGI protocol.15 unmodified lines58 @app.route("/")59 def hello():60 return "Hello World!"61 41-client = httpx.Client(app=app)42-r = client.get('http://example/')43-assert r.status_code == 20044-assert r.text == "Hello World!"62+with httpx.Client(app=app) as client:63+ r = client.get('http://example/')64+ assert r.status_code == 20065+ assert r.text == "Hello World!"66 ```67 68 For some more complex cases you might need to customize the WSGI or ASGI69 dispatch. This allows you to:6 unmodified lines76 77 ```python78 # Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4".79 dispatch = httpx.dispatch.WSGIDispatch(app=app, remote_addr="1.2.3.4")59-client = httpx.Client(dispatch=dispatch)80+with httpx.Client(dispatch=dispatch) as client:81+ ...82 ```83 84 ## Build Request85 86 You can use `Client.build_request()` to build a request and87 make modifications before sending the request.88 89 ```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 ```98 99 ## Specify the version of the HTTP protocol2 unmodified lines102 103 For example:104 105 ```python82-h11_client = httpx.Client(http_versions=["HTTP/1.1"])83-h11_response = h11_client.get("https://myserver.com")106+with httpx.Client(http_versions=["HTTP/1.1"]) as h11_client:107+ h11_response = h11_client.get("https://myserver.com")108 85-h2_client = httpx.Client(http_versions=["HTTP/2"])86-h2_response = h2_client.get("https://myserver.com")109+with httpx.Client(http_versions=["HTTP/2"]) as h2_client:110+ h2_response = h2_client.get("https://myserver.com")111 ```112 113 ## .netrc Support114 34 unmodified lines149 For example to forward all HTTP traffic to `http://127.0.0.1:3080` and all HTTPS traffic150 to `http://127.0.0.1:3081` your `proxies` config would look like this:151 152 ```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 ```160 161 Proxies can be configured for a specific scheme and host, all schemes of a host,162 all hosts for a scheme, or for all requests. When determining which proxy configuration163 to use for a given request this same order is used.164 165 ```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 ```179 180 !!! warning181 To make sure that proxies cannot read your traffic,10 unmodified lines192 proxy = httpx.HTTPProxy(193 proxy_url="https://127.0.0.1",194 proxy_mode=httpx.HTTPProxyMode.TUNNEL_ONLY195 )165-client = httpx.Client(proxies=proxy)166-167-# This request will be tunneled instead of forwarded.168-client.get("http://example.com")196+with httpx.Client(proxies=proxy) as client:197+ # This request will be tunneled instead of forwarded.198+ r = client.get("http://example.com")199 ```200 201 202 ## Timeout fine-tuning16 unmodified lines219 # Using top-level API220 httpx.get('http://example.com/api/v1/example', timeout=5)221 222 # Or, with a client:193-client = httpx.Client()194-client.get("http://example.com/api/v1/example", timeout=5)223+with httpx.Client() as client:224+ client.get("http://example.com/api/v1/example", timeout=5)225 ```226 227 - On a client instance, which results in the given `timeout` being used as a default for requests made with this client:228 229 ```python200-client = httpx.Client(timeout=5)201-client.get('http://example.com/api/v1/example')230+with httpx.Client(timeout=5) as client:231+ client.get('http://example.com/api/v1/example')232 ```233 234 Besides, you can pass timeouts in two forms:235 22 unmodified lines258 259 httpx.get(url, timeout=None) # Times out after 5s260 261 232-client = httpx.Client(timeout=None)233-client.get(url) # Does not timeout, returns after 10s262+with httpx.Client(timeout=None) as client:263+ client.get(url) # Does not timeout, returns after 10s264 265 266 timeout = httpx.TimeoutConfig(267 connect_timeout=5, 268 read_timeout=None, 269 write_timeout=5270 )271 httpx.get(url, timeout=timeout) # Does not timeout, returns after 10s242-```272+```modified:docs/api.md+2 added-2 removed
21 unmodified lines222324252627262728293031132 unmodified linesExpand all21 unmodified lines
*An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.*
```python>>> client = httpx.Client()>>> response = client.get('https://example.org')>>> with httpx.Client() as client:... response = client.get('https://example.org')```
* `def __init__([auth], [params], [headers], [cookies], [verify], [cert], [timeout], [pool_limits], [max_redirects], [app], [dispatch])`* `.params` - **QueryParams**132 unmodified linesExpand allmodified:docs/compatibility.md+2 added-1 removed
25 unmodified lines2627282930303132333425 unmodified lines
is equivalent to
```pythonclient = httpx.Client(**kwargs)with httpx.Client(**kwargs) as client: ...```
More detailed documentation and usage of `Client` can be found in [Advanced Usage](advanced.md).modified:docs/environment_variables.md+6 added-6 removed
24 unmodified lines25 Example:26 27 ```python28 # test_script.py29-29 import httpx31-client = httpx.Client()32-client.get("https://google.com")30+31+with httpx.Client() as client:32+ r = client.get("https://google.com")33 ```34 35 ```console36 user@host:~$ HTTPX_DEBUG=1 python test_script.py26 unmodified lines63 Example:64 65 ```python66 # test_script.py67-67 import httpx69-client = httpx.Client()70-client.get("https://google.com")68+69+with httpx.Client() as client:70+ r = client.get("https://google.com")71 ```72 73 ```console74 SSLKEYLOGFILE=test.log python test_script.py57 unmodified linesmodified:docs/parallel.md+9 added-9 removed
46 unmodified lines47 control the authentication or dispatch behavior for all requests within the48 block.49 50 ```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 ```55 56 ## Async parallel requests57 58 If you're working within an async framework, then you'll want to use a fully59 async API for making requests.60 61 ```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 ```69 70 See [the Async Client documentation](async.md) for more details.