advanced.md
This file
Path
docs/advanced.md
468 lines · 15.9 KiB · Markdown
Last changed by
Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
History of this fileTake it
The walk stopped after 200 commits: lines older than 5ced56b point at it.
Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
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 back11Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
lines 12–16why, one step back12!!! note13 Starting from `httpx==0.10.0`, the default and recommended Client class is `AsyncClient`. This should help prevent breaking changes once sync support is reintroduced.1415 A `Client` synonym remains for compatibility with `httpx==0.9.*` releases, but you are encouraged to migrate to `AsyncClient` as soon as possible.16Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 17–20why, one step back17### Usage1819The 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:20Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
line 21why, one step back21```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 22–23why, one step back22>>> with httpx.Client() as client:23... r = client.get('https://example.com')Drop sync (#544)Tom Christiebefore adoption206c537
line 24why, one step back24...Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 25–28why, one step back25>>> r26<Response [200 OK]>27```28Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 29why, one step back29Alternatively, you can explicitly close the connection pool without block-usage using `.close()`:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 30–31why, one step back3031```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 32why, one step back32>>> client = httpx.Client()Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 33why, one step back33>>> try:Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 34why, one step back34... r = client.get('https://example.com')Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 35why, one step back35... finally:Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 36why, one step back36... client.close()Drop sync (#544)Tom Christiebefore adoption206c537
line 37why, one step back37...Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
lines 38–41why, one step back38>>> r39<Response [200 OK]>40```41Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 42–43why, one step back42Once you have a `Client`, you can use all the features documented in the [Quickstart](/quickstart) guide.43Document client-level configuration (#488)Florimond Mancabefore adoptionad38db8
lines 44–52why, one step back44### Configuration4546Clients allow you to apply configuration to all outgoing requests by passing parameters to the `Client` constructor.4748For example, to apply a set of custom headers on every request:4950```python51>>> url = 'http://httpbin.org/headers'52>>> headers = {'user-agent': 'my-app/0.0.1'}Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 53–54why, one step back53>>> with httpx.Client(headers=headers) as client:54... r = client.get(url)Document client-level configuration (#488)Florimond Mancabefore adoptionad38db8
lines 55–61why, one step back55...56>>> r.json()['headers']['User-Agent']57'my-app/0.0.1'58```5960!!! note61 When you provide a parameter at both the client and request levels, one of two things can happen:Drop sync (#544)Tom Christiebefore adoption206c537
line 62why, one step back62Document client-level configuration (#488)Florimond Mancabefore adoptionad38db8
lines 63–65why, one step back63 - For headers, query parameters and cookies, the values are merged into one.64 - For all other parameters, the request-level value is used.65Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 66why, one step back66Additionally, `Client` accepts some parameters that aren't available at the request level.Document client-level configuration (#488)Florimond Mancabefore adoptionad38db8
lines 67–70why, one step back6768One particularly useful parameter is `base_url`, which allows you to define a base URL to prepend to all outgoing requests:6970```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 71–72why, one step back71>>> with httpx.Client(base_url='http://httpbin.org') as client:72... r = client.get('/headers')Drop sync (#544)Tom Christiebefore adoption206c537
line 73why, one step back73...Document client-level configuration (#488)Florimond Mancabefore adoptionad38db8
lines 74–77why, one step back74>>> r.request.url75URL('http://httpbin.org/headers')76```77Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 78why, one step back78For a list of all available client-level parameters, see the [`Client` API reference](/api/#client).Document client-level configuration (#488)Florimond Mancabefore adoptionad38db8
line 79why, one step back79Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
lines 80–81why, one step back80## Calling into Python Web Apps81Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 82why, one step back82You can configure an `httpx` client to call directly into a Python web application using the WSGI protocol.Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
lines 83–85why, one step back8384This is particularly useful for two main use-cases:85Fix some grammar in Advanced docs (#461)thebigmunchbefore adoption3917866
lines 86–87why, one step back86* Using `httpx` as a client inside test cases.87* Mocking out external services during tests or in dev/staging environments.Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
line 88why, one step back88Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 89why, one step back89Here's an example of integrating against a Flask application:Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
lines 90–91why, one step back9091```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 92–93why, one step back92from flask import Flask93import httpxExpose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
lines 94–95why, one step back9495Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 96why, one step back96app = Flask(__name__)Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
line 97why, one step back97Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 98–100why, one step back98@app.route("/")99def hello():100 return "Hello World!"Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
line 101why, one step back101Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 102–105why, one step back102with httpx.Client(app=app) as client:103 r = client.get('http://example/')104 assert r.status_code == 200105 assert r.text == "Hello World!"Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
lines 106–107why, one step back106```107Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 108why, one step back108For some more complex cases you might need to customize the WSGI dispatch. This allows you to:Drop sync (#544)Tom Christiebefore adoption206c537
line 109why, one step back109Fix some grammar in Advanced docs (#461)thebigmunchbefore adoption3917866
line 110why, one step back110* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 111–112why, one step back111* Mount the WSGI application at a subpath by setting `script_name` (WSGI).112* Use a given client address for requests by setting `remote_addr` (WSGI).Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
lines 113–116why, one step back113114For example:115116```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 117–119why, one step back117# Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4".118dispatch = httpx.WSGIDispatch(app=app, remote_addr="1.2.3.4")119with httpx.Client(dispatch=dispatch) as client:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 120why, one step back120 ...Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
line 121why, one step back121```Link to ASGI docs (#577)Tom Christiebefore adoption7d45db0
line 122why, one step back122Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
lines 123–128why, one step back123## Build Request124125You can use `Client.build_request()` to build a request and126make modifications before sending the request.127128```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 129why, one step back129>>> with httpx.Client() as client:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 130–131why, one step back130... req = client.build_request("OPTIONS", "https://example.com")131... req.url.full_path = "*" # Build an 'OPTIONS *' request for CORSProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 132why, one step back132... r = client.send(req)Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 133–134why, one step back133...134>>> rExpose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
lines 135–142why, one step back135<Response [200 OK]>136```137138## .netrc Support139140HTTPX supports .netrc file. In `trust_env=True` cases, if auth parameter is141not defined, HTTPX tries to add auth into request's header from .netrc file.142Cache netrc authentication per-client (#400)Can Sarıgölbefore adoption84731c8
lines 143–147why, one step back143!!! note144 The NETRC file is cached across requests made by a client.145 If you need to refresh the cache (e.g. because the NETRC file has changed),146 you should create a new client or restart the interpreter.147Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
lines 148–149why, one step back148As default `trust_env` is true. To set false:149```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 150why, one step back150>>> httpx.get('https://example.org/', trust_env=False)Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
lines 151–170why, one step back151```152153If `NETRC` environment is empty, HTTPX tries to use default files.154(`~/.netrc`, `~/_netrc`)155156To change `NETRC` environment:157```python158>>> import os159>>> os.environ["NETRC"] = "my_default_folder/.my_netrc"160```161162.netrc file content example:163```164machine netrcexample.org165login example-username166password example-password167168...169```170Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855
lines 171–173why, one step back171When using `Client` instances, `trust_env` should be set on the client itself, rather that on the request methods:172173```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 174why, one step back174client = httpx.Client(trust_env=False)Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855
lines 175–176why, one step back175```176Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
lines 177–183why, one step back177## HTTP Proxying178179HTTPX supports setting up proxies the same way that Requests does via the `proxies` parameter.180For example to forward all HTTP traffic to `http://127.0.0.1:3080` and all HTTPS traffic181to `http://127.0.0.1:3081` your `proxies` config would look like this:182183```pythonDocument client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 184–187why, one step back184>>> proxies = {185... "http": "http://127.0.0.1:3080",186... "https": "http://127.0.0.1:3081"187... }Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 188why, one step back188>>> with httpx.Client(proxies=proxies) as client:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 189why, one step back189... ...Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
lines 190–196why, one step back190```191192Proxies can be configured for a specific scheme and host, all schemes of a host,193all hosts for a scheme, or for all requests. When determining which proxy configuration194to use for a given request this same order is used.195196```pythonDocument client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 197–202why, one step back197>>> proxies = {198... "http://example.com": "...", # Host+Scheme199... "all://example.com": "...", # Host200... "http": "...", # Scheme201... "all": "...", # All202... }Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 203why, one step back203>>> with httpx.Client(proxies=proxies) as client:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 204why, one step back204... ...Drop sync (#544)Tom Christiebefore adoption206c537
line 205why, one step back205...Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 206why, one step back206>>> proxy = "..." # Shortcut for {'all': '...'}Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 207why, one step back207>>> with httpx.Client(proxies=proxy) as client:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 208why, one step back208... ...Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
lines 209–215why, one step back209```210211!!! warning212 To make sure that proxies cannot read your traffic,213 and even if the proxy_url uses HTTPS, it is recommended to214 use HTTPS and tunnel requests if possible.215Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 216why, one step back216By default `httpx.Proxy` will operate as a forwarding proxy for `http://...` requestsExpose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
line 217why, one step back217and will establish a `CONNECT` TCP tunnel for `https://` requests. This doesn't changeProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 218why, one step back218regardless of the proxy `url` being `http` or `https`.Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
lines 219–222why, one step back219220Proxies can be configured to have different behavior such as forwarding or tunneling all requests:221222```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 223–225why, one step back223proxy = httpx.Proxy(224 url="https://127.0.0.1",225 mode="TUNNEL_ONLY" # May be "TUNNEL_ONLY" or "FORWARD_ONLY". Defaults to "DEFAULT".Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
line 226why, one step back226)Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 227why, one step back227with httpx.Client(proxies=proxy) as client:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 228why, one step back228 # This request will be tunneled instead of forwarded.Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 229why, one step back229 r = client.get("http://example.com")Expose ASGIDispatch & WSGIDispatch in the 'dispatch' namespace. (#407)Ahmed Maherbefore adoption5ced56b
line 230why, one step back230```Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 231why, one step back231Drop proxies parameter from the high level API (#485)Yeray Diaz Diazbefore adoption09db6ec
lines 232–233why, one step back232!!! note233Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 234–235why, one step back234 To use proxies you must pass the proxy information at `Client` initialization,235 rather than on the `.get(...)` call or other request methods.Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 236why, one step back236Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 237why, one step back237## Timeout ConfigurationAdd timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 238why, one step back238Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 239why, one step back239HTTPX is careful to enforce timeouts everywhere by default.Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 240why, one step back240Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 241–242why, one step back241The default behavior is to raise a `TimeoutException` after 5 seconds of242network inactivity.Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 243why, one step back243Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 244why, one step back244### Setting and disabling timeoutsMultipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 245why, one step back245Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 246why, one step back246You can set timeouts for an individual request:Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 247–248why, one step back247248```pythonAllow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 249why, one step back249# Using the top-level API:Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 250why, one step back250httpx.get('http://example.com/api/v1/example', timeout=10.0)Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 251why, one step back251Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 252why, one step back252# Using a client instance:Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 253–254why, one step back253with httpx.Client() as client:254 client.get("http://example.com/api/v1/example", timeout=10.0)Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 255–256why, one step back255```256Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 257why, one step back257Or disable timeouts for an individual request:Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 258–259why, one step back258259```pythonAllow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 260why, one step back260# Using the top-level API:Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 261why, one step back261httpx.get('http://example.com/api/v1/example', timeout=None)Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 262–263why, one step back262263# Using a client instance:Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 264–265why, one step back264with httpx.Client() as client:265 client.get("http://example.com/api/v1/example", timeout=None)Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 266–267why, one step back266```267Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 268why, one step back268### Setting a default timeout on a clientAdd timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 269why, one step back269Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 270–271why, one step back270You can set a timeout on a client instance, which results in the given271`timeout` being used as the default for requests made with this client:Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 272–273why, one step back272273```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 274–276why, one step back274client = httpx.Client() # Use a default 5s timeout everywhere.275client = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.276client = httpx.Client(timeout=None) # Disable all timeouts by default.Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 277–278why, one step back277```278Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 279why, one step back279### Fine tuning the configurationMultipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 280why, one step back280Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 281why, one step back281HTTPX also allows you to specify the timeout behavior in more fine grained detail.Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 282why, one step back282Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 283–284why, one step back283There are four different types of timeouts that may occur. These are **connect**,284**read**, **write**, and **pool** timeouts.Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 285why, one step back285Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 286–299why, one step back286* The **connect timeout** specifies the maximum amount of time to wait until287a connection to the requested host is established. If HTTPX is unable to connect288within this time frame, a `ConnectTimeout` exception is raised.289* The **read timeout** specifies the maximum duration to wait for a chunk of290data to be received (for example, a chunk of the response body). If HTTPX is291unable to receive data within this time frame, a `ReadTimeout` exception is raised.292* The **write timeout** specifies the maximum duration to wait for a chunk of293data to be sent (for example, a chunk of the request body). If HTTPX is unable294to send data within this time frame, a `WriteTimeout` exception is raised.295* The **pool timeout** specifies the maximum duration to wait for acquiring296a connection from the connection pool. If HTTPX is unable to acquire a connection297within this time frame, a `PoolTimeout` exception is raised. A related298configuration here is the maximum number of allowable connections in the299connection pool, which is configured by the `pool_limits`.Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 300why, one step back300Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 301–302why, one step back301You can configure the timeout behavior for any of these values...302Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 303why, one step back303```pythonAllow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 304–305why, one step back304# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.305timeout = httpx.Timeout(10.0, connect_timeout=60.0)Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 306why, one step back306client = httpx.Client(timeout=timeout)Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 307why, one step back307Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 308why, one step back308response = client.get('http://example.com/')Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
lines 309–314why, one step back309```310311## Multipart file encoding312313As mentioned in the [quickstart](/quickstart#sending-multipart-file-uploads)314multipart file encoding is available by passing a dictionary with theClarify multipart documentation (#580)Mattwmaster58before adoption33cb397
line 315why, one step back315name of the payloads as keys and either tuple of elements or a file-like object or a string as values.Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
lines 316–318why, one step back316317```python318>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 319why, one step back319>>> r = httpx.post("https://httpbin.org/post", files=files)Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
lines 320–329why, one step back320>>> print(r.text)321{322 ...323 "files": {324 "upload-file": "<... binary content ...>"325 },326 ...327}328```329Clarify multipart documentation (#580)Mattwmaster58before adoption33cb397
line 330why, one step back330More specifically, if a tuple is used as a value, it must have between 2 and 3 elements:Update advanced.mdTom Christiebefore adoption871b0b5
line 331why, one step back331Clarify multipart documentation (#580)Mattwmaster58before adoption33cb397
lines 332–333why, one step back332- The first element is an optional file name which can be set to `None`.333- The second element may be a file-like object or a string which will be automaticallyMultipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 334why, one step back334encoded in UTF-8.Better HTTP/2 defaults. (#584)Tom Christiebefore adoption30229f1
line 335why, one step back335- An optional third element can be used to specify theMultipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 336why, one step back336[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)Clarify multipart documentation (#580)Mattwmaster58before adoption33cb397
lines 337–340why, one step back337of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based338on the file name, with unknown file extensions defaulting to "application/octet-stream".339If the file name is explicitly set to `None` then HTTPX will not include a content-type340MIME header field.Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
lines 341–343why, one step back341342```python343>>> files = {'upload-file': (None, 'text content', 'text/plain')}Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 344why, one step back344>>> r = httpx.post("https://httpbin.org/post", files=files)Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
lines 345–353why, one step back345>>> print(r.text)346{347 ...348 "files": {},349 "form": {350 "upload-file": "text-content"351 },352 ...353}Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 354why, one step back354```Add docs on SSL certificates (#510)Florimond Mancabefore adoption95b2b24
line 355why, one step back355Public Auth API (#732)Tom Christiebefore adoption12dd157
lines 356–418why, one step back356## Customizing authentication357358When issuing requests or instantiating a client, the `auth` argument can be used to pass an authentication scheme to use. The `auth` argument may be one of the following...359360* A two-tuple of `username`/`password`, to be used with basic authentication.361* An instance of `httpx.BasicAuth()` or `httpx.DigestAuth()`.362* A callable, accepting a request and returning an authenticated request instance.363* A subclass of `httpx.Auth`.364365The most involved of these is the last, which allows you to create authentication flows involving one or more requests. A subclass of `httpx.Auth` should implement `def auth_flow(request)`, and yield any requests that need to be made...366367```python368class MyCustomAuth(httpx.Auth):369 def __init__(self, token):370 self.token = token371372 def auth_flow(self, request):373 # Send the request, with a custom `X-Authentication` header.374 request.headers['X-Authentication'] = self.token375 yield request376```377378If the auth flow requires more that one request, you can issue multiple yields, and obtain the response in each case...379380```python381class MyCustomAuth(httpx.Auth):382 def __init__(self, token):383 self.token = token384385 def auth_flow(self, request):386 response = yield request387 if response.status_code == 401:388 # If the server issues a 401 response then resend the request,389 # with a custom `X-Authentication` header.390 request.headers['X-Authentication'] = self.token391 yield request392```393394Custom authentication classes are designed to not perform any I/O, so that they may be used with both sync and async client instances. If you are implementing an authentication scheme that requires the request body, then you need to indicate this on the class using a `requires_request_body` property.395396You will then be able to access `request.content` inside the `.auth_flow()` method.397398```python399class MyCustomAuth(httpx.Auth):400 requires_request_body = True401402 def __init__(self, token):403 self.token = token404405 def auth_flow(self, request):406 response = yield request407 if response.status_code == 401:408 # If the server issues a 401 response then resend the request,409 # with a custom `X-Authentication` header.410 request.headers['X-Authentication'] = self.sign_request(...)411 yield request412413 def sign_request(self, request):414 # Create a request signature, based on `request.method`, `request.url`,415 # `request.headers`, and `request.content`.416 ...417```418Add docs on SSL certificates (#510)Florimond Mancabefore adoption95b2b24
lines 419–422why, one step back419## SSL certificates420421When making a request over HTTPS, HTTPX needs to verify the identity of the requested host. To do this, it uses a bundle of SSL certificates (a.k.a. CA bundle) delivered by a trusted certificate authority (CA).422Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855
line 423why, one step back423### Changing the verification defaultsAdd docs on SSL certificates (#510)Florimond Mancabefore adoption95b2b24
lines 424–426why, one step back424425By default, HTTPX uses the CA bundle provided by [Certifi](https://pypi.org/project/certifi/). This is what you want in most cases, even though some advanced situations may require you to use a different set of certificates.426Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855
line 427why, one step back427If you'd like to use a custom CA bundle, you can use the `verify` parameter.Add docs on SSL certificates (#510)Florimond Mancabefore adoption95b2b24
lines 428–431why, one step back428429```python430import httpx431Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 432why, one step back432r = httpx.get("https://example.org", verify="path/to/client.pem")Add docs on SSL certificates (#510)Florimond Mancabefore adoption95b2b24
line 433why, one step back433```Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855
lines 434–439why, one step back434435You can also disable the SSL verification...436437```python438import httpx439Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 440why, one step back440r = httpx.get("https://example.org", verify=False)Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855
lines 441–447why, one step back441```442443### SSL configuration on client instances444445If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.446447```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 448why, one step back448client = httpx.Client(verify=False)Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855
lines 449–450why, one step back449```450Update advanced.mdTom Christiebefore adoptionddc4885
line 451why, one step back451The `client.get(...)` method and other request methods *do not* support changing the SSL settings on a per-request basis. If you need different SSL settings in different cases you should use more that one client instance, with different settings on each. Each client will then be using an isolated connection pool with a specific fixed SSL configuration on all connections within that pool.Add docs on SSL certificates (#510)Florimond Mancabefore adoption95b2b24
lines 452–464why, one step back452453### Making HTTPS requests to a local server454455When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.456457If you do need to make HTTPS connections to a local server, for example to test an HTTPS-only service, you will need to create and use your own certificates. Here's one way to do it:4584591. Use [trustme-cli](https://github.com/sethmlarson/trustme-cli/) to generate a pair of server key/cert files, and a client cert file.4601. Pass the server key/cert files when starting your local server. (This depends on the particular web server you're using. For example, [Uvicorn](https://www.uvicorn.org) provides the `--ssl-keyfile` and `--ssl-certfile` options.)4611. Tell HTTPX to use the certificates stored in `client.pem`:462463```python464>>> import httpxProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 465why, one step back465>>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")Add docs on SSL certificates (#510)Florimond Mancabefore adoption95b2b24
lines 466–468why, one step back466>>> r467Response <200 OK>468```