advanced.md
This file
Path
docs/advanced.md
473 lines · 16.1 KiB · Markdown
Last changed by
Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
History of this fileTake it
The walk stopped after 200 commits: lines older than 31730e7 point at it.
Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
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:20Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
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...Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
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 back79Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
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.Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
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.Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
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:Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
lines 90–91why, one step back9091```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 92–93why, one step back92from flask import Flask93import httpxAdd documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
lines 94–95why, one step back9495Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 96why, one step back96app = Flask(__name__)Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
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!"Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
line 101why, one step back101Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 102–103why, one step back102with httpx.Client(app=app, base_url="http://testserver") as client:103 r = client.get("/")Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 104–105why, one step back104 assert r.status_code == 200105 assert r.text == "Hello World!"Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
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).Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
lines 113–116why, one step back113114For example:115116```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 117–118why, 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")Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
line 119why, one step back119with httpx.Client(dispatch=dispatch, base_url="http://testserver") as client:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 120why, one step back120 ...Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
line 121why, one step back121```Link to ASGI docs (#577)Tom Christiebefore adoption7d45db0
line 122why, one step back122Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
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>>> rAdd documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
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.147Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
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)Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
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```176Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
lines 177–178why, one step back177## HTTP Proxying178Detect credentials in proxy URLs and create Proxy-authorization header (#780)Yeray Diaz Diazbefore adoptionb234203
line 179why, one step back179HTTPX supports setting up HTTP proxies the same way that Requests does via the `proxies` parameter.Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
lines 180–183why, one step back180For 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... ...Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
lines 190–191why, one step back190```191Detect credentials in proxy URLs and create Proxy-authorization header (#780)Yeray Diaz Diazbefore adoptionb234203
lines 192–194why, one step back192Credentials may be passed in as part of the URL in the standard way, i.e.193`http://username:password@127.0.0.1:3080`.194Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
lines 195–199why, one step back195Proxies can be configured for a specific scheme and host, all schemes of a host,196all hosts for a scheme, or for all requests. When determining which proxy configuration197to use for a given request this same order is used.198199```pythonDocument client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 200–205why, one step back200>>> proxies = {201... "http://example.com": "...", # Host+Scheme202... "all://example.com": "...", # Host203... "http": "...", # Scheme204... "all": "...", # All205... }Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 206why, one step back206>>> with httpx.Client(proxies=proxies) as client:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 207why, one step back207... ...Drop sync (#544)Tom Christiebefore adoption206c537
line 208why, one step back208...Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 209why, one step back209>>> proxy = "..." # Shortcut for {'all': '...'}Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 210why, one step back210>>> with httpx.Client(proxies=proxy) as client:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 211why, one step back211... ...Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
lines 212–218why, one step back212```213214!!! warning215 To make sure that proxies cannot read your traffic,216 and even if the proxy_url uses HTTPS, it is recommended to217 use HTTPS and tunnel requests if possible.218Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 219why, one step back219By default `httpx.Proxy` will operate as a forwarding proxy for `http://...` requestsAdd documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
line 220why, one step back220and will establish a `CONNECT` TCP tunnel for `https://` requests. This doesn't changeProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 221why, one step back221regardless of the proxy `url` being `http` or `https`.Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
lines 222–225why, one step back222223Proxies can be configured to have different behavior such as forwarding or tunneling all requests:224225```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 226–228why, one step back226proxy = httpx.Proxy(227 url="https://127.0.0.1",228 mode="TUNNEL_ONLY" # May be "TUNNEL_ONLY" or "FORWARD_ONLY". Defaults to "DEFAULT".Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
line 229why, one step back229)Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 230why, one step back230with httpx.Client(proxies=proxy) as client:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 231why, one step back231 # This request will be tunneled instead of forwarded.Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 232why, one step back232 r = client.get("http://example.com")Add documentation for requests.Session compatibility (#449)Jt Miclatbefore adoption31730e7
line 233why, one step back233```Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 234why, one step back234Drop proxies parameter from the high level API (#485)Yeray Diaz Diazbefore adoption09db6ec
lines 235–236why, one step back235!!! note236Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 237–238why, one step back237 To use proxies you must pass the proxy information at `Client` initialization,238 rather than on the `.get(...)` call or other request methods.Detect credentials in proxy URLs and create Proxy-authorization header (#780)Yeray Diaz Diazbefore adoptionb234203
lines 239–240why, one step back239240SOCKS proxies are *not* supported yet.Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 241why, one step back241Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 242why, one step back242## Timeout ConfigurationAdd timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 243why, one step back243Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 244why, one step back244HTTPX is careful to enforce timeouts everywhere by default.Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 245why, one step back245Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 246–247why, one step back246The default behavior is to raise a `TimeoutException` after 5 seconds of247network inactivity.Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 248why, one step back248Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 249why, one step back249### Setting and disabling timeoutsMultipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 250why, one step back250Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 251why, one step back251You can set timeouts for an individual request:Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 252–253why, one step back252253```pythonAllow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 254why, one step back254# Using the top-level API:Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 255why, one step back255httpx.get('http://example.com/api/v1/example', timeout=10.0)Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 256why, one step back256Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 257why, one step back257# Using a client instance:Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 258–259why, one step back258with httpx.Client() as client:259 client.get("http://example.com/api/v1/example", timeout=10.0)Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 260–261why, one step back260```261Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 262why, one step back262Or disable timeouts for an individual request:Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 263–264why, one step back263264```pythonAllow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 265why, one step back265# Using the top-level API:Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 266why, one step back266httpx.get('http://example.com/api/v1/example', timeout=None)Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 267–268why, one step back267268# Using a client instance:Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 269–270why, one step back269with httpx.Client() as client:270 client.get("http://example.com/api/v1/example", timeout=None)Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 271–272why, one step back271```272Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 273why, one step back273### Setting a default timeout on a clientAdd timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 274why, one step back274Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 275–276why, one step back275You can set a timeout on a client instance, which results in the given276`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 277–278why, one step back277278```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
lines 279–281why, one step back279client = httpx.Client() # Use a default 5s timeout everywhere.280client = httpx.Client(timeout=10.0) # Use a default 10s timeout everywhere.281client = httpx.Client(timeout=None) # Disable all timeouts by default.Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 282–283why, one step back282```283Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 284why, one step back284### Fine tuning the configurationMultipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 285why, one step back285Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 286why, one step back286HTTPX also allows you to specify the timeout behavior in more fine grained detail.Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 287why, one step back287Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 288–289why, one step back288There are four different types of timeouts that may occur. These are **connect**,289**read**, **write**, and **pool** timeouts.Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 290why, one step back290Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 291–304why, one step back291* The **connect timeout** specifies the maximum amount of time to wait until292a connection to the requested host is established. If HTTPX is unable to connect293within this time frame, a `ConnectTimeout` exception is raised.294* The **read timeout** specifies the maximum duration to wait for a chunk of295data to be received (for example, a chunk of the response body). If HTTPX is296unable to receive data within this time frame, a `ReadTimeout` exception is raised.297* The **write timeout** specifies the maximum duration to wait for a chunk of298data to be sent (for example, a chunk of the request body). If HTTPX is unable299to send data within this time frame, a `WriteTimeout` exception is raised.300* The **pool timeout** specifies the maximum duration to wait for acquiring301a connection from the connection pool. If HTTPX is unable to acquire a connection302within this time frame, a `PoolTimeout` exception is raised. A related303configuration here is the maximum number of allowable connections in the304connection pool, which is configured by the `pool_limits`.Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 305why, one step back305Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 306–307why, one step back306You can configure the timeout behavior for any of these values...307Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 308why, one step back308```pythonAllow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 309–310why, one step back309# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.310timeout = httpx.Timeout(10.0, connect_timeout=60.0)Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 311why, one step back311client = httpx.Client(timeout=timeout)Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 312why, one step back312Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 313why, one step back313response = client.get('http://example.com/')Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
lines 314–319why, one step back314```315316## Multipart file encoding317318As mentioned in the [quickstart](/quickstart#sending-multipart-file-uploads)319multipart file encoding is available by passing a dictionary with theClarify multipart documentation (#580)Mattwmaster58before adoption33cb397
line 320why, one step back320name 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 321–323why, one step back321322```python323>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 324why, one step back324>>> r = httpx.post("https://httpbin.org/post", files=files)Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
lines 325–334why, one step back325>>> print(r.text)326{327 ...328 "files": {329 "upload-file": "<... binary content ...>"330 },331 ...332}333```334Clarify multipart documentation (#580)Mattwmaster58before adoption33cb397
line 335why, one step back335More specifically, if a tuple is used as a value, it must have between 2 and 3 elements:Update advanced.mdTom Christiebefore adoption871b0b5
line 336why, one step back336Clarify multipart documentation (#580)Mattwmaster58before adoption33cb397
lines 337–338why, one step back337- The first element is an optional file name which can be set to `None`.338- The second element may be a file-like object or a string which will be automaticallyMultipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 339why, one step back339encoded in UTF-8.Better HTTP/2 defaults. (#584)Tom Christiebefore adoption30229f1
line 340why, one step back340- An optional third element can be used to specify theMultipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 341why, one step back341[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)Clarify multipart documentation (#580)Mattwmaster58before adoption33cb397
lines 342–345why, one step back342of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based343on the file name, with unknown file extensions defaulting to "application/octet-stream".344If the file name is explicitly set to `None` then HTTPX will not include a content-type345MIME header field.Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
lines 346–348why, one step back346347```python348>>> files = {'upload-file': (None, 'text content', 'text/plain')}Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 349why, one step back349>>> r = httpx.post("https://httpbin.org/post", files=files)Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
lines 350–358why, one step back350>>> print(r.text)351{352 ...353 "files": {},354 "form": {355 "upload-file": "text-content"356 },357 ...358}Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 359why, one step back359```Add docs on SSL certificates (#510)Florimond Mancabefore adoption95b2b24
line 360why, one step back360Public Auth API (#732)Tom Christiebefore adoption12dd157
lines 361–423why, one step back361## Customizing authentication362363When 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...364365* A two-tuple of `username`/`password`, to be used with basic authentication.366* An instance of `httpx.BasicAuth()` or `httpx.DigestAuth()`.367* A callable, accepting a request and returning an authenticated request instance.368* A subclass of `httpx.Auth`.369370The 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...371372```python373class MyCustomAuth(httpx.Auth):374 def __init__(self, token):375 self.token = token376377 def auth_flow(self, request):378 # Send the request, with a custom `X-Authentication` header.379 request.headers['X-Authentication'] = self.token380 yield request381```382383If the auth flow requires more that one request, you can issue multiple yields, and obtain the response in each case...384385```python386class MyCustomAuth(httpx.Auth):387 def __init__(self, token):388 self.token = token389390 def auth_flow(self, request):391 response = yield request392 if response.status_code == 401:393 # If the server issues a 401 response then resend the request,394 # with a custom `X-Authentication` header.395 request.headers['X-Authentication'] = self.token396 yield request397```398399Custom 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.400401You will then be able to access `request.content` inside the `.auth_flow()` method.402403```python404class MyCustomAuth(httpx.Auth):405 requires_request_body = True406407 def __init__(self, token):408 self.token = token409410 def auth_flow(self, request):411 response = yield request412 if response.status_code == 401:413 # If the server issues a 401 response then resend the request,414 # with a custom `X-Authentication` header.415 request.headers['X-Authentication'] = self.sign_request(...)416 yield request417418 def sign_request(self, request):419 # Create a request signature, based on `request.method`, `request.url`,420 # `request.headers`, and `request.content`.421 ...422```423Add docs on SSL certificates (#510)Florimond Mancabefore adoption95b2b24
lines 424–427why, one step back424## SSL certificates425426When 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).427Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855
line 428why, one step back428### Changing the verification defaultsAdd docs on SSL certificates (#510)Florimond Mancabefore adoption95b2b24
lines 429–431why, one step back429430By 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.431Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855
line 432why, one step back432If 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 433–436why, one step back433434```python435import httpx436Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 437why, one step back437r = httpx.get("https://example.org", verify="path/to/client.pem")Add docs on SSL certificates (#510)Florimond Mancabefore adoption95b2b24
line 438why, one step back438```Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855
lines 439–444why, one step back439440You can also disable the SSL verification...441442```python443import httpx444Proposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 445why, one step back445r = httpx.get("https://example.org", verify=False)Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855
lines 446–452why, one step back446```447448### SSL configuration on client instances449450If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.451452```pythonProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 453why, one step back453client = httpx.Client(verify=False)Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855
lines 454–455why, one step back454```455Update advanced.mdTom Christiebefore adoptionddc4885
line 456why, one step back456The `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 457–469why, one step back457458### Making HTTPS requests to a local server459460When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.461462If 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:4634641. Use [trustme-cli](https://github.com/sethmlarson/trustme-cli/) to generate a pair of server key/cert files, and a client cert file.4651. 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.)4661. Tell HTTPX to use the certificates stored in `client.pem`:467468```python469>>> import httpxProposed 0.11 docs (#727)Tom Christiebefore adoption2038919
line 470why, one step back470>>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")Add docs on SSL certificates (#510)Florimond Mancabefore adoption95b2b24
lines 471–473why, one step back471>>> r472Response <200 OK>473```