advanced.md
This file
Path
docs/advanced.md
485 lines · 16.0 KiB · Markdown
Last changed by
Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
History of this fileTake it
The walk stopped after 200 commits: lines older than 57c27ca point at it.
Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
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:20Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
line 21why, one step back21```pythonRename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 22why, one step back22>>> async with httpx.AsyncClient() as client:Drop sync (#544)Tom Christiebefore adoption206c537
lines 23–24why, one step back23... r = await client.get('https://example.com')24...Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 25–28why, one step back25>>> r26<Response [200 OK]>27```28Rename 'close' to 'aclose' on Client (#675)Florimond Mancabefore adoptiond5da743
line 29why, one step back29Alternatively, you can explicitly close the connection pool without block-usage using `.aclose()`:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 30–31why, one step back3031```pythonRename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 32why, one step back32>>> client = httpx.AsyncClient()Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 33why, one step back33>>> try:Drop sync (#544)Tom Christiebefore adoption206c537
line 34why, one step back34... r = await client.get('https://example.com')Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 35why, one step back35... finally:Rename 'close' to 'aclose' on Client (#675)Florimond Mancabefore adoptiond5da743
line 36why, one step back36... await client.aclose()Drop sync (#544)Tom Christiebefore adoption206c537
line 37why, one step back37...Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
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'}Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 53why, one step back53>>> async with httpx.AsyncClient(headers=headers) as client:Drop sync (#544)Tom Christiebefore adoption206c537
line 54why, one step back54... r = await 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```pythonRename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 71why, one step back71>>> async with httpx.AsyncClient(base_url='http://httpbin.org') as client:Drop sync (#544)Tom Christiebefore adoption206c537
lines 72–73why, one step back72... r = await client.get('/headers')73...Document client-level configuration (#488)Florimond Mancabefore adoptionad38db8
lines 74–77why, one step back74>>> r.request.url75URL('http://httpbin.org/headers')76```77Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 78why, one step back78For a list of all available client-level parameters, see the [`AsyncClient` API reference](/api/#async-client).Document client-level configuration (#488)Florimond Mancabefore adoptionad38db8
line 79why, one step back79Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 80–82why, one step back80## Calling into Python Web Apps8182You can configure an `httpx` client to call directly into a Python webLink to ASGI docs (#577)Tom Christiebefore adoption7d45db0
line 83why, one step back83application using the ASGI protocol.Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 84–86why, one step back8485This is particularly useful for two main use-cases:86Fix some grammar in Advanced docs (#461)thebigmunchbefore adoption3917866
lines 87–88why, one step back87* Using `httpx` as a client inside test cases.88* Mocking out external services during tests or in dev/staging environments.Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
line 89why, one step back89Drop sync (#544)Tom Christiebefore adoption206c537
line 90why, one step back90Let's take this Starlette application as an example:Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 91–92why, one step back9192```pythonDrop sync (#544)Tom Christiebefore adoption206c537
lines 93–95why, one step back93from starlette.applications import Starlette94from starlette.responses import HTMLResponse95from starlette.routing import RouteImplement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 96–97why, one step back9697Drop sync (#544)Tom Christiebefore adoption206c537
lines 98–99why, one step back98async def hello():99 return HTMLResponse("Hello World!")Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 100–101why, one step back100101Drop sync (#544)Tom Christiebefore adoption206c537
line 102why, one step back102app = Starlette(routes=[Route("/", hello)])Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 103–104why, one step back103```104Drop sync (#544)Tom Christiebefore adoption206c537
lines 105–108why, one step back105We can make requests directly against the application, like so:106107```python108>>> import httpxRename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 109why, one step back109>>> async with httpx.AsyncClient(app=app) as client:Drop sync (#544)Tom Christiebefore adoption206c537
lines 110–114why, one step back110... r = client.get('http://example/')111... assert r.status_code == 200112... assert r.text == "Hello World!"113```114Link to ASGI docs (#577)Tom Christiebefore adoption7d45db0
line 115why, one step back115For some more complex cases you might need to customise the ASGI dispatch. This allows you to:Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
line 116why, one step back116Fix some grammar in Advanced docs (#461)thebigmunchbefore adoption3917866
line 117why, one step back117* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.Link to ASGI docs (#577)Tom Christiebefore adoption7d45db0
line 118why, one step back118* Mount the ASGI application at a subpath by setting `root_path`.Drop sync (#544)Tom Christiebefore adoption206c537
line 119why, one step back119* Use a given client address for requests by setting `client`.Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 120–123why, one step back120121For example:122123```pythonLink to ASGI docs (#577)Tom Christiebefore adoption7d45db0
lines 124–126why, one step back124# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",125# on port 123.126dispatch = httpx.dispatch.ASGIDispatch(app=app, client=("1.2.3.4", 123))Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 127why, one step back127async with httpx.AsyncClient(dispatch=dispatch) as client:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 128why, one step back128 ...Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
line 129why, one step back129```Link to ASGI docs (#577)Tom Christiebefore adoption7d45db0
lines 130–132why, one step back130131See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path`132keys.Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 133–139why, one step back133134## Build Request135136You can use `Client.build_request()` to build a request and137make modifications before sending the request.138139```pythonRename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 140why, one step back140>>> async with httpx.AsyncClient() as client:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 141–142why, one step back141... req = client.build_request("OPTIONS", "https://example.com")142... req.url.full_path = "*" # Build an 'OPTIONS *' request for CORSDrop sync (#544)Tom Christiebefore adoption206c537
line 143why, one step back143... r = await client.send(req)Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 144–145why, one step back144...145>>> rImplement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 146–153why, one step back146<Response [200 OK]>147```148149## .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.158Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 159–160why, one step back159As default `trust_env` is true. To set false:160```pythonDrop sync (#544)Tom Christiebefore adoption206c537
line 161why, one step back161>>> await httpx.get('https://example.org/', trust_env=False)Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 162–180why, one step back162```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
line 181why, one step back181Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855
lines 182–184why, one step back182When using `Client` instances, `trust_env` should be set on the client itself, rather that on the request methods:183184```pythonRename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 185why, one step back185client = httpx.AsyncClient(trust_env=False)Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855
lines 186–187why, one step back186```187Add Unix Domain Sockets section to advanced docs page (#542)Jonas Lundbergbefore adoptionf0e6acb
lines 188–197why, one step back188## Unix Domain Sockets189190You can configure an `httpx` client to connect through a unix domain socket via the `uds` parameter. This is useful when making requests to a server that is bound to a socket file rather than an IP address.191192Here's an example requesting the Docker Engine API:193194```python195import httpx196197Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 198why, one step back198async with httpx.AsyncClient(uds="/var/run/docker.sock") as client:Add Unix Domain Sockets section to advanced docs page (#542)Jonas Lundbergbefore adoptionf0e6acb
line 199why, one step back199 # This request will connect through the socket file.Drop sync (#544)Tom Christiebefore adoption206c537
line 200why, one step back200 resp = await client.get("http://localhost/version")Add Unix Domain Sockets section to advanced docs page (#542)Jonas Lundbergbefore adoptionf0e6acb
lines 201–202why, one step back201```202Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085
lines 203–209why, one step back203## HTTP Proxying204205HTTPX supports setting up proxies the same way that Requests does via the `proxies` parameter.206For example to forward all HTTP traffic to `http://127.0.0.1:3080` and all HTTPS traffic207to `http://127.0.0.1:3081` your `proxies` config would look like this:208209```pythonDocument client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 210–213why, one step back210>>> proxies = {211... "http": "http://127.0.0.1:3080",212... "https": "http://127.0.0.1:3081"213... }Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 214why, one step back214>>> async with httpx.AsyncClient(proxies=proxies) as client:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 215why, one step back215... ...Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085
lines 216–222why, one step back216```217218Proxies can be configured for a specific scheme and host, all schemes of a host,219all hosts for a scheme, or for all requests. When determining which proxy configuration220to use for a given request this same order is used.221222```pythonDocument client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
lines 223–228why, one step back223>>> proxies = {224... "http://example.com": "...", # Host+Scheme225... "all://example.com": "...", # Host226... "http": "...", # Scheme227... "all": "...", # All228... }Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 229why, one step back229>>> async with httpx.AsyncClient(proxies=proxies) as client:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 230why, one step back230... ...Drop sync (#544)Tom Christiebefore adoption206c537
line 231why, one step back231...Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 232why, one step back232>>> proxy = "..." # Shortcut for {'all': '...'}Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 233why, one step back233>>> async with httpx.AsyncClient(proxies=proxy) as client:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 234why, one step back234... ...Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085
lines 235–250why, one step back235```236237!!! warning238 To make sure that proxies cannot read your traffic,239 and even if the proxy_url uses HTTPS, it is recommended to240 use HTTPS and tunnel requests if possible.241242By default `HTTPProxy` will operate as a forwarding proxy for `http://...` requests243and will establish a `CONNECT` TCP tunnel for `https://` requests. This doesn't change244regardless of the `proxy_url` being `http` or `https`.245246Proxies can be configured to have different behavior such as forwarding or tunneling all requests:247248```python249proxy = httpx.HTTPProxy(250 proxy_url="https://127.0.0.1",Tighten up top-level API to only expose public API (#608)Tom Christiebefore adoptiond15dc0b
line 251why, one step back251 proxy_mode="TUNNEL_ONLY" # May be "TUNNEL_ONLY" or "FORWARD_ONLY". Defaults to "DEFAULT".Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085
line 252why, one step back252)Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 253why, one step back253async with httpx.AsyncClient(proxies=proxy) as client:Document client block-usage and close() (#487)Florimond Mancabefore adoption074cd25
line 254why, one step back254 # This request will be tunneled instead of forwarded.Drop sync (#544)Tom Christiebefore adoption206c537
line 255why, one step back255 r = await client.get("http://example.com")Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085
line 256why, one step back256```Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 257why, one step back257Drop proxies parameter from the high level API (#485)Yeray Diaz Diazbefore adoption09db6ec
lines 258–262why, one step back258!!! note259260 Per request proxy configuration, i.e. `client.get(url, proxies=...)`,261 has not been implemented yet. To use proxies you must pass the proxy262 information at `Client` initialization.Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 263why, one step back263Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 264why, one step back264## Timeout ConfigurationAdd timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 265why, one step back265Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 266why, one step back266HTTPX is careful to enforce timeouts everywhere by default.Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 267why, one step back267Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 268–269why, one step back268The default behavior is to raise a `TimeoutException` after 5 seconds of269network inactivity.Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 270why, one step back270Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 271why, one step back271### Setting and disabling timeoutsMultipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 272why, one step back272Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 273why, one step back273You can set timeouts for an individual request:Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 274–275why, one step back274275```pythonAllow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 276–277why, one step back276# Using the top-level API:277await httpx.get('http://example.com/api/v1/example', timeout=10.0)Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 278why, one step back278Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 279why, one step back279# Using a client instance:Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 280why, one step back280async with httpx.AsyncClient() as client:Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 281why, one step back281 await client.get("http://example.com/api/v1/example", timeout=10.0)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 back284Or disable timeouts for an individual request:Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 285–286why, one step back285286```pythonAllow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 287–290why, one step back287# Using the top-level API:288await httpx.get('http://example.com/api/v1/example', timeout=None)289290# Using a client instance:Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 291why, one step back291async with httpx.AsyncClient() as client:Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 292why, one step back292 await client.get("http://example.com/api/v1/example", timeout=None)Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 293–294why, one step back293```294Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 295why, one step back295### Setting a default timeout on a clientAdd timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 296why, one step back296Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 297–298why, one step back297You can set a timeout on a client instance, which results in the given298`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 299–300why, one step back299300```pythonRename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
lines 301–303why, one step back301client = httpx.AsyncClient() # Use a default 5s timeout everywhere.302client = httpx.AsyncClient(timeout=10.0) # Use a default 10s timeout everywhere.303client = httpx.AsyncClient(timeout=None) # Disable all timeouts by default.Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
lines 304–305why, one step back304```305Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 306why, one step back306### Fine tuning the configurationMultipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 307why, one step back307Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 308why, one step back308HTTPX also allows you to specify the timeout behavior in more fine grained detail.Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 309why, one step back309Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 310–311why, one step back310There are four different types of timeouts that may occur. These are **connect**,311**read**, **write**, and **pool** timeouts.Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 312why, one step back312Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 313–326why, one step back313* The **connect timeout** specifies the maximum amount of time to wait until314a connection to the requested host is established. If HTTPX is unable to connect315within this time frame, a `ConnectTimeout` exception is raised.316* The **read timeout** specifies the maximum duration to wait for a chunk of317data to be received (for example, a chunk of the response body). If HTTPX is318unable to receive data within this time frame, a `ReadTimeout` exception is raised.319* The **write timeout** specifies the maximum duration to wait for a chunk of320data to be sent (for example, a chunk of the request body). If HTTPX is unable321to send data within this time frame, a `WriteTimeout` exception is raised.322* The **pool timeout** specifies the maximum duration to wait for acquiring323a connection from the connection pool. If HTTPX is unable to acquire a connection324within this time frame, a `PoolTimeout` exception is raised. A related325configuration here is the maximum number of allowable connections in the326connection pool, which is configured by the `pool_limits`.Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 327why, one step back327Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 328–329why, one step back328You can configure the timeout behavior for any of these values...329Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 330why, one step back330```pythonAllow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
lines 331–332why, one step back331# A client with a 60s timeout for connecting, and a 10s timeout elsewhere.332timeout = httpx.Timeout(10.0, connect_timeout=60.0)Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 333why, one step back333client = httpx.AsyncClient(timeout=timeout)Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 334why, one step back334Allow default+override timeout style (#593)Tom Christiebefore adoption2f54b20
line 335why, one step back335response = await client.get('http://example.com/')Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
lines 336–341why, one step back336```337338## Multipart file encoding339340As mentioned in the [quickstart](/quickstart#sending-multipart-file-uploads)341multipart file encoding is available by passing a dictionary with theClarify multipart documentation (#580)Mattwmaster58before adoption33cb397
line 342why, one step back342name 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 343–345why, one step back343344```python345>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}Drop sync (#544)Tom Christiebefore adoption206c537
line 346why, one step back346>>> r = await httpx.post("https://httpbin.org/post", files=files)Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
lines 347–356why, one step back347>>> print(r.text)348{349 ...350 "files": {351 "upload-file": "<... binary content ...>"352 },353 ...354}355```356Clarify multipart documentation (#580)Mattwmaster58before adoption33cb397
line 357why, one step back357More specifically, if a tuple is used as a value, it must have between 2 and 3 elements:Update advanced.mdTom Christiebefore adoption871b0b5
line 358why, one step back358Clarify multipart documentation (#580)Mattwmaster58before adoption33cb397
lines 359–360why, one step back359- The first element is an optional file name which can be set to `None`.360- The second element may be a file-like object or a string which will be automaticallyMultipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 361why, one step back361encoded in UTF-8.Better HTTP/2 defaults. (#584)Tom Christiebefore adoption30229f1
line 362why, one step back362- An optional third element can be used to specify theMultipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
line 363why, one step back363[MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_Types)Clarify multipart documentation (#580)Mattwmaster58before adoption33cb397
lines 364–367why, one step back364of the file being uploaded. If not specified HTTPX will attempt to guess the MIME type based365on the file name, with unknown file extensions defaulting to "application/octet-stream".366If the file name is explicitly set to `None` then HTTPX will not include a content-type367MIME header field.Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
lines 368–370why, one step back368369```python370>>> files = {'upload-file': (None, 'text content', 'text/plain')}Drop sync (#544)Tom Christiebefore adoption206c537
line 371why, one step back371>>> r = await httpx.post("https://httpbin.org/post", files=files)Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
lines 372–380why, one step back372>>> print(r.text)373{374 ...375 "files": {},376 "form": {377 "upload-file": "text-content"378 },379 ...380}Add timeout fine-tunning advanced docs section (#476)Mateusz Wośbefore adoption2984499
line 381why, one step back381```Add docs on SSL certificates (#510)Florimond Mancabefore adoption95b2b24
lines 382–386why, one step back382383## SSL certificates384385When 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).386Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855
line 387why, one step back387### Changing the verification defaultsAdd docs on SSL certificates (#510)Florimond Mancabefore adoption95b2b24
lines 388–390why, one step back388389By 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.390Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855
line 391why, one step back391If 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 392–395why, one step back392393```python394import httpx395Drop sync (#544)Tom Christiebefore adoption206c537
line 396why, one step back396r = await httpx.get("https://example.org", verify="path/to/client.pem")Add docs on SSL certificates (#510)Florimond Mancabefore adoption95b2b24
line 397why, one step back397```Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855
lines 398–411why, one step back398399You can also disable the SSL verification...400401```python402import httpx403404r = await httpx.get("https://example.org", verify=False)405```406407### SSL configuration on client instances408409If you're using a `Client()` instance, then you should pass any SSL settings when instantiating the client.410411```pythonRename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 412why, one step back412client = httpx.AsyncClient(verify=False)Warn if cert / verify / trust_env are passed to client.request() (#597)Tom Christiebefore adoption1e23855
lines 413–414why, one step back413```414Update advanced.mdTom Christiebefore adoptionddc4885
line 415why, one step back415The `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 416–428why, one step back416417### Making HTTPS requests to a local server418419When making requests to local servers, such as a development server running on `localhost`, you will typically be using unencrypted HTTP connections.420421If 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:4224231. Use [trustme-cli](https://github.com/sethmlarson/trustme-cli/) to generate a pair of server key/cert files, and a client cert file.4241. 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.)4251. Tell HTTPX to use the certificates stored in `client.pem`:426427```python428>>> import httpxDrop sync (#544)Tom Christiebefore adoption206c537
line 429why, one step back429>>> r = await httpx.get("https://localhost:8000", verify="/tmp/client.pem")Add docs on SSL certificates (#510)Florimond Mancabefore adoption95b2b24
lines 430–432why, one step back430>>> r431Response <200 OK>432```Drop sync (#544)Tom Christiebefore adoption206c537
line 433why, one step back433Improve backend docs, particularly wrt. autodetection (#595)Tom Christiebefore adoptionf8794cb
line 434why, one step back434## Supported async environmentsDrop sync (#544)Tom Christiebefore adoption206c537
line 435why, one step back435Improve backend docs, particularly wrt. autodetection (#595)Tom Christiebefore adoptionf8794cb
line 436why, one step back436HTTPX supports either `asyncio` or `trio` as an async environment.Drop sync (#544)Tom Christiebefore adoption206c537
line 437why, one step back437Improve backend docs, particularly wrt. autodetection (#595)Tom Christiebefore adoptionf8794cb
lines 438–439why, one step back438By default it will auto-detect which of those two to use as the backend439for socket operations and concurrency primitives.Drop sync (#544)Tom Christiebefore adoption206c537
line 440why, one step back440Improve backend docs, particularly wrt. autodetection (#595)Tom Christiebefore adoptionf8794cb
lines 441–442why, one step back441You can also explicitly select a backend by instantiating a client with the442`backend` argument...Drop sync (#544)Tom Christiebefore adoption206c537
line 443why, one step back443Improve backend docs, particularly wrt. autodetection (#595)Tom Christiebefore adoptionf8794cb
line 444why, one step back444```pythonRename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
lines 445–447why, one step back445client = httpx.AsyncClient(backend='auto') # Autodetection. The default case.446client = httpx.AsyncClient(backend='asyncio') # Use asyncio as the backend.447client = httpx.AsyncClient(backend='trio') # Use trio as the backend.Improve backend docs, particularly wrt. autodetection (#595)Tom Christiebefore adoptionf8794cb
line 448why, one step back448```Drop sync (#544)Tom Christiebefore adoption206c537
line 449why, one step back449Improve backend docs, particularly wrt. autodetection (#595)Tom Christiebefore adoptionf8794cb
lines 450–454why, one step back450### [AsyncIO](https://docs.python.org/3/library/asyncio.html)451452AsyncIO is Python's [built-in library](https://docs.python.org/3/library/asyncio.html)453for writing concurrent code with the async/await syntax.454Drop sync (#544)Tom Christiebefore adoption206c537
line 455why, one step back455```pythonImprove backend docs, particularly wrt. autodetection (#595)Tom Christiebefore adoptionf8794cb
line 456why, one step back456import asyncioDrop sync (#544)Tom Christiebefore adoption206c537
lines 457–459why, one step back457import httpx458459async def main():Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 460why, one step back460 client = httpx.AsyncClient()Improve backend docs, particularly wrt. autodetection (#595)Tom Christiebefore adoptionf8794cb
lines 461–462why, one step back461 response = await client.get('https://www.example.com/')462 print(response)Drop sync (#544)Tom Christiebefore adoption206c537
line 463why, one step back463Improve backend docs, particularly wrt. autodetection (#595)Tom Christiebefore adoptionf8794cb
lines 464–476why, one step back464asyncio.run(main())465```466467### [Trio](https://github.com/python-trio/trio)468469Trio is [an alternative async library](https://trio.readthedocs.io/en/stable/),470designed around the [the principles of structured concurrency](https://en.wikipedia.org/wiki/Structured_concurrency).471472```python473import httpx474import trio475476async def main():Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 477why, one step back477 client = httpx.AsyncClient()Improve backend docs, particularly wrt. autodetection (#595)Tom Christiebefore adoptionf8794cb
lines 478–480why, one step back478 response = await client.get('https://www.example.com/')479 print(response)480Drop sync (#544)Tom Christiebefore adoption206c537
lines 481–484why, one step back481trio.run(main)482```483484!!! importantImprove backend docs, particularly wrt. autodetection (#595)Tom Christiebefore adoptionf8794cb
line 485why, one step back485 The `trio` package must be installed to use the Trio backend.