Skip to content
Myr

Add the 'proxy' parameter and deprecate 'proxies'. (#2879)

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

* Add the proxy parameter and deprecate proxies * Make the Client.proxy and HTTPTransport.proxy types the same * Update httpx/_transports/default.py Co-authored-by: T-256 <132141463+T-256@users.noreply.github.com> * Update httpx/_transports/default.py Co-authored-by: T-256 <132141463+T-256@users.noreply.github.com> * Drop unneeded noqa * Changelog * update documentation * Allow None in mounts * typos * Update httpx/_types.py * Changes proxies to proxy in CLI app * Add proxy to request function * Update CHANGELOG.md Co-authored-by: Tom Christie <tom@tomchristie.com> * Update docs/troubleshooting.md Co-authored-by: Tom Christie <tom@tomchristie.com> * Update docs/troubleshooting.md Co-authored-by: Tom Christie <tom@tomchristie.com> * Lint ---------

authored by Kar Petrosyan · committed by GitHub · parent b471f01 · Browse files · 11 files+281 added−170 removed
This commit

State

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

Trailers

  • Co-authored-by: Tom Christie <tom@tomchristie.com>
  • Co-authored-by: T-256 <132141463+T-256@users.noreply.github.com>

Diff stats

11 files+281 added−170 removed

  • tests:+63 added−11 removed
  • other:+218 added−159 removed

11 files+281 added−170 removed

modified:docs/advanced.md+132 added-132 removed
502 unmodified lines
503The `NetRCAuth()` class uses [the `netrc.netrc()` function from the Python standard library](https://docs.python.org/3/library/netrc.html). See the documentation there for more details on exceptions that may be raised if the netrc file is not found, or cannot be parsed.504505## HTTP Proxying506507HTTPX supports setting up [HTTP proxies](https://en.wikipedia.org/wiki/Proxy_server#Web_proxy_servers) via the `proxies` parameter to be passed on client initialization or top-level API functions like `httpx.get(..., proxies=...)`.507HTTPX supports setting up [HTTP proxies](https://en.wikipedia.org/wiki/Proxy_server#Web_proxy_servers) via the `proxy` parameter to be passed on client initialization or top-level API functions like `httpx.get(..., proxy=...)`.508509<div align="center">510 <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/27/Open_proxy_h2g2bob.svg/480px-Open_proxy_h2g2bob.svg.png"/>511 <figcaption><em>Diagram of how a proxy works (source: Wikipedia). The left hand side "Internet" blob may be your HTTPX client requesting <code>example.com</code> through a proxy.</em></figcaption>
3 unmodified lines
515516To route all traffic (HTTP and HTTPS) to a proxy located at `http://localhost:8030`, pass the proxy URL to the client...517518```python519with httpx.Client(proxies="http://localhost:8030") as client:519with httpx.Client(proxy="http://localhost:8030") as client:520 ...521```522523For more advanced use cases, pass a proxies `dict`. For example, to route HTTP and HTTPS requests to 2 different proxies, respectively located at `http://localhost:8030`, and `http://localhost:8031`, pass a `dict` of proxy URLs:523For more advanced use cases, pass a mounts `dict`. For example, to route HTTP and HTTPS requests to 2 different proxies, respectively located at `http://localhost:8030`, and `http://localhost:8031`, pass a `dict` of proxy URLs:524525```python526proxies = {527 "http://": "http://localhost:8030",528 "https://": "http://localhost:8031",526proxy_mounts = {527 "http://": httpx.HTTPTransport(proxy="http://localhost:8030"),528 "https://": httpx.HTTPTransport(proxy="http://localhost:8031"),529}530531with httpx.Client(proxies=proxies) as client:531with httpx.Client(mounts=proxy_mounts) as client:532 ...533```534535For detailed information about proxy routing, see the [Routing](#routing) section.
9 unmodified lines
545546Proxy credentials can be passed as the `userinfo` section of the proxy URL. For example:547548```python549proxies = {550 "http://": "http://username:password@localhost:8030",551 # ...552}549with httpx.Client(proxy="http://username:password@localhost:8030") as client:550 ...551```552555### Routing556557HTTPX provides fine-grained controls for deciding which requests should go through a proxy, and which shouldn't. This process is known as proxy routing.558559The `proxies` dictionary maps URL patterns ("proxy keys") to proxy URLs. HTTPX matches requested URLs against proxy keys to decide which proxy should be used, if any. Matching is done from most specific proxy keys (e.g. `https://<domain>:<port>`) to least specific ones (e.g. `https://`).560561HTTPX supports routing proxies based on **scheme**, **domain**, **port**, or a combination of these.562563#### Wildcard routing564565Route everything through a proxy...566567```python568proxies = {569 "all://": "http://localhost:8030",570}571```572573#### Scheme routing574575Route HTTP requests through one proxy, and HTTPS requests through another...576577```python578proxies = {579 "http://": "http://localhost:8030",580 "https://": "http://localhost:8031",581}582```583584#### Domain routing585586Proxy all requests on domain "example.com", let other requests pass through...587588```python589proxies = {590 "all://example.com": "http://localhost:8030",591}592```593594Proxy HTTP requests on domain "example.com", let HTTPS and other requests pass through...595596```python597proxies = {598 "http://example.com": "http://localhost:8030",599}600```601602Proxy all requests to "example.com" and its subdomains, let other requests pass through...603604```python605proxies = {606 "all://*example.com": "http://localhost:8030",607}608```609610Proxy all requests to strict subdomains of "example.com", let "example.com" and other requests pass through...611612```python613proxies = {614 "all://*.example.com": "http://localhost:8030",615}616```617618#### Port routing619620Proxy HTTPS requests on port 1234 to "example.com"...621622```python623proxies = {624 "https://example.com:1234": "http://localhost:8030",625}626```627628Proxy all requests on port 1234...629630```python631proxies = {632 "all://*:1234": "http://localhost:8030",633}634```635636#### No-proxy support637638It is also possible to define requests that _shouldn't_ be routed through proxies.639640To do so, pass `None` as the proxy URL. For example...641642```python643proxies = {644 # Route requests through a proxy by default...645 "all://": "http://localhost:8031",646 # Except those for "example.com".647 "all://example.com": None,648}649```650651#### Complex configuration example652653You can combine the routing features outlined above to build complex proxy routing configurations. For example...654655```python656proxies = {657 # Route all traffic through a proxy by default...658 "all://": "http://localhost:8030",659 # But don't use proxies for HTTPS requests to "domain.io"...660 "https://domain.io": None,661 # And use another proxy for requests to "example.com" and its subdomains...662 "all://*example.com": "http://localhost:8031",663 # And yet another proxy if HTTP is used,664 # and the "internal" subdomain on port 5550 is requested...665 "http://internal.example.com:5550": "http://localhost:8032",666}667```668669#### Environment variables670671HTTP proxying can also be configured through environment variables, although with less fine-grained control.672673See documentation on [`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`](environment_variables.md#http_proxy-https_proxy-all_proxy) for more information.674553### Proxy mechanisms554555!!! note556 This section describes **advanced** proxy concepts and functionality.
27 unmodified lines
584585You can now configure a client to make requests via a proxy using the SOCKS protocol:586587```python710httpx.Client(proxies='socks5://user:pass@host:port')588httpx.Client(proxy='socks5://user:pass@host:port')589```590591## Timeout Configuration592
578 unmodified lines
1171# Support URLs like "file:///Users/sylvia_green/websites/new_client/index.html"1172mounts = {"file://": FileSystemTransport()}1173client = httpx.Client(mounts=mounts)1174```11751176### Routing11771178HTTPX provides a powerful mechanism for routing requests, allowing you to write complex rules that specify which transport should be used for each request.11791180The `mounts` dictionary maps URL patterns to HTTP transports. HTTPX matches requested URLs against URL patterns to decide which transport should be used, if any. Matching is done from most specific URL patterns (e.g. `https://<domain>:<port>`) to least specific ones (e.g. `https://`).11811182HTTPX supports routing requests based on **scheme**, **domain**, **port**, or a combination of these.11831184#### Wildcard routing11851186Route everything through a transport...11871188```python1189mounts = {1190 "all://": httpx.HTTPTransport(proxy="http://localhost:8030"),1191}1192```11931194#### Scheme routing11951196Route HTTP requests through one transport, and HTTPS requests through another...11971198```python1199mounts = {1200 "http://": httpx.HTTPTransport(proxy="http://localhost:8030"),1201 "https://": httpx.HTTPTransport(proxy="http://localhost:8031"),1202}1203```12041205#### Domain routing12061207Proxy all requests on domain "example.com", let other requests pass through...12081209```python1210mounts = {1211 "all://example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),1212}1213```12141215Proxy HTTP requests on domain "example.com", let HTTPS and other requests pass through...12161217```python1218mounts = {1219 "http://example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),1220}1221```12221223Proxy all requests to "example.com" and its subdomains, let other requests pass through...12241225```python1226mounts = {1227 "all://*example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),1228}1229```12301231Proxy all requests to strict subdomains of "example.com", let "example.com" and other requests pass through...12321233```python1234mounts = {1235 "all://*.example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),1236}1237```12381239#### Port routing12401241Proxy HTTPS requests on port 1234 to "example.com"...12421243```python1244mounts = {1245 "https://example.com:1234": httpx.HTTPTransport(proxy="http://localhost:8030"),1246}1247```12481249Proxy all requests on port 1234...12501251```python1252mounts = {1253 "all://*:1234": httpx.HTTPTransport(proxy="http://localhost:8030"),1254}1255```12561257#### No-proxy support12581259It is also possible to define requests that _shouldn't_ be routed through the transport.12601261To do so, pass `None` as the proxy URL. For example...12621263```python1264mounts = {1265 # Route requests through a proxy by default...1266 "all://": httpx.HTTPTransport(proxy="http://localhost:8031"),1267 # Except those for "example.com".1268 "all://example.com": None,1269}1270```12711272#### Complex configuration example12731274You can combine the routing features outlined above to build complex proxy routing configurations. For example...12751276```python1277mounts = {1278 # Route all traffic through a proxy by default...1279 "all://": httpx.HTTPTransport(proxy="http://localhost:8030"),1280 # But don't use proxies for HTTPS requests to "domain.io"...1281 "https://domain.io": None,1282 # And use another proxy for requests to "example.com" and its subdomains...1283 "all://*example.com": httpx.HTTPTransport(proxy="http://localhost:8031"),1284 # And yet another proxy if HTTP is used,1285 # and the "internal" subdomain on port 5550 is requested...1286 "http://internal.example.com:5550": httpx.HTTPTransport(proxy="http://localhost:8032"),1287}1288```12891290#### Environment variables12911292There are also environment variables that can be used to control the dictionary of the client mounts. 1293They can be used to configure HTTP proxying for clients.12941295See documentation on [`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`](environment_variables.md#http_proxy-https_proxy-all_proxy) for more information.1296
modified:docs/compatibility.md+8 added-4 removed
155 unmodified lines
156```157158## Proxy keys159160When using `httpx.Client(proxies={...})` to map to a selection of different proxies, we use full URL schemes, such as `proxies={"http://": ..., "https://": ...}`.160HTTPX uses the mounts argument for HTTP proxying and transport routing.161It can do much more than proxies and allows you to configure more than just the proxy route.162For more detailed documentation, see [Mounting Transports](advanced.md#mounting-transports).163164When using `httpx.Client(mounts={...})` to map to a selection of different transports, we use full URL schemes, such as `mounts={"http://": ..., "https://": ...}`.165166This is different to the `requests` usage of `proxies={"http": ..., "https": ...}`.167164This change is for better consistency with more complex mappings, that might also include domain names, such as `proxies={"all://": ..., "all://www.example.com": None}` which maps all requests onto a proxy, except for requests to "www.example.com" which have an explicit exclusion.168This change is for better consistency with more complex mappings, that might also include domain names, such as `mounts={"all://": ..., httpx.HTTPTransport(proxy="all://www.example.com": None})` which maps all requests onto a proxy, except for requests to "www.example.com" which have an explicit exclusion.169166Also note that `requests.Session.request(...)` allows a `proxies=...` parameter, whereas `httpx.Client.request(...)` does not.170Also note that `requests.Session.request(...)` allows a `proxies=...` parameter, whereas `httpx.Client.request(...)` does not allow `mounts=...`.171172## SSL configuration173174When using a `Client` instance, the `trust_env`, `verify`, and `cert` arguments should always be passed on client instantiation, rather than passed to the request method.
23 unmodified lines
198## Request instantiation199200There is no notion of [prepared requests](https://requests.readthedocs.io/en/stable/user/advanced/#prepared-requests) in HTTPX. If you need to customize request instantiation, see [Request instances](advanced.md#request-instances).201198Besides, `httpx.Request()` does not support the `auth`, `timeout`, `follow_redirects`, `proxies`, `verify` and `cert` parameters. However these are available in `httpx.request`, `httpx.get`, `httpx.post` etc., as well as on [`Client` instances](advanced.md#client-instances).202Besides, `httpx.Request()` does not support the `auth`, `timeout`, `follow_redirects`, `mounts`, `verify` and `cert` parameters. However these are available in `httpx.request`, `httpx.get`, `httpx.post` etc., as well as on [`Client` instances](advanced.md#client-instances).203204## Mocking205206If you need to mock HTTPX the same way that test utilities like `responses` and `requests-mock` does for `requests`, see [RESPX](https://github.com/lundberg/respx).
24 unmodified lines
modified:docs/contributing.md+1 added-3 removed
211 unmodified lines
212213```214import httpx215216proxies = {"all://": "http://127.0.0.1:8080/"}217218with httpx.Client(proxies=proxies, verify="/path/to/client.pem") as client:216with httpx.Client(proxy="http://127.0.0.1:8080/", verify="/path/to/client.pem") as client:217 response = client.get("https://example.org")218 print(response.status_code) # should print 200219```220
15 unmodified lines
modified:docs/troubleshooting.md+9 added-7 removed
modified:httpx/_transports/default.py+6 added-3 removed
45 unmodified lines
46 WriteError,47 WriteTimeout,48)49from .._models import Request, Response50from .._types import AsyncByteStream, CertTypes, SyncByteStream, VerifyTypes50from .._types import AsyncByteStream, CertTypes, ProxyTypes, SyncByteStream, VerifyTypes51from .._urls import URL52from .base import AsyncBaseTransport, BaseTransport5354T = typing.TypeVar("T", bound="HTTPTransport")55A = typing.TypeVar("A", bound="AsyncHTTPTransport")
68 unmodified lines
124 http1: bool = True,125 http2: bool = False,126 limits: Limits = DEFAULT_LIMITS,127 trust_env: bool = True,127 proxy: typing.Optional[Proxy] = None,128 proxy: typing.Optional[ProxyTypes] = None,129 uds: typing.Optional[str] = None,130 local_address: typing.Optional[str] = None,131 retries: int = 0,132 socket_options: typing.Optional[typing.Iterable[SOCKET_OPTION]] = None,133 ) -> None:134 ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)135 proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy136137 if proxy is None:138 self._pool = httpcore.ConnectionPool(139 ssl_context=ssl_context,
125 unmodified lines
265 http1: bool = True,266 http2: bool = False,267 limits: Limits = DEFAULT_LIMITS,268 trust_env: bool = True,267 proxy: typing.Optional[Proxy] = None,269 proxy: typing.Optional[ProxyTypes] = None,270 uds: typing.Optional[str] = None,271 local_address: typing.Optional[str] = None,272 retries: int = 0,273 socket_options: typing.Optional[typing.Iterable[SOCKET_OPTION]] = None,274 ) -> None:275 ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)276 proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy277278 if proxy is None:279 self._pool = httpcore.AsyncConnectionPool(280 ssl_context=ssl_context,
103 unmodified lines
modified:httpx/_api.py+20 added
8 unmodified lines
9 CertTypes,10 CookieTypes,11 HeaderTypes,12 ProxiesTypes,13 ProxyTypes,14 QueryParamTypes,15 RequestContent,16 RequestData,17 RequestFiles,
14 unmodified lines
32 json: typing.Optional[typing.Any] = None,33 headers: typing.Optional[HeaderTypes] = None,34 cookies: typing.Optional[CookieTypes] = None,35 auth: typing.Optional[AuthTypes] = None,36 proxy: typing.Optional[ProxyTypes] = None,37 proxies: typing.Optional[ProxiesTypes] = None,38 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,39 follow_redirects: bool = False,40 verify: VerifyTypes = True,
23 unmodified lines
64 * **cookies** - *(optional)* Dictionary of Cookie items to include in the65 request.66 * **auth** - *(optional)* An authentication class to use when sending the67 request.68 * **proxy** - *(optional)* A proxy URL where all the traffic should be routed.69 * **proxies** - *(optional)* A dictionary mapping proxy keys to proxy URLs.70 * **timeout** - *(optional)* The timeout configuration to use when sending71 the request.72 * **follow_redirects** - *(optional)* Enables or disables HTTP redirects.
20 unmodified lines
93 ```94 """95 with Client(96 cookies=cookies,97 proxy=proxy,98 proxies=proxies,99 cert=cert,100 verify=verify,101 timeout=timeout,
25 unmodified lines
127 json: typing.Optional[typing.Any] = None,128 headers: typing.Optional[HeaderTypes] = None,129 cookies: typing.Optional[CookieTypes] = None,130 auth: typing.Optional[AuthTypes] = None,131 proxy: typing.Optional[ProxyTypes] = None,132 proxies: typing.Optional[ProxiesTypes] = None,133 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,134 follow_redirects: bool = False,135 verify: VerifyTypes = True,
11 unmodified lines
147 [0]: /quickstart#streaming-responses148 """149 with Client(150 cookies=cookies,151 proxy=proxy,152 proxies=proxies,153 cert=cert,154 verify=verify,155 timeout=timeout,
20 unmodified lines
176 params: typing.Optional[QueryParamTypes] = None,177 headers: typing.Optional[HeaderTypes] = None,178 cookies: typing.Optional[CookieTypes] = None,179 auth: typing.Optional[AuthTypes] = None,180 proxy: typing.Optional[ProxyTypes] = None,181 proxies: typing.Optional[ProxiesTypes] = None,182 follow_redirects: bool = False,183 cert: typing.Optional[CertTypes] = None,184 verify: VerifyTypes = True,
14 unmodified lines
199 params=params,200 headers=headers,201 cookies=cookies,202 auth=auth,203 proxy=proxy,204 proxies=proxies,205 follow_redirects=follow_redirects,206 cert=cert,207 verify=verify,
8 unmodified lines
216 params: typing.Optional[QueryParamTypes] = None,217 headers: typing.Optional[HeaderTypes] = None,218 cookies: typing.Optional[CookieTypes] = None,219 auth: typing.Optional[AuthTypes] = None,220 proxy: typing.Optional[ProxyTypes] = None,221 proxies: typing.Optional[ProxiesTypes] = None,222 follow_redirects: bool = False,223 cert: typing.Optional[CertTypes] = None,224 verify: VerifyTypes = True,
14 unmodified lines
239 params=params,240 headers=headers,241 cookies=cookies,242 auth=auth,243 proxy=proxy,244 proxies=proxies,245 follow_redirects=follow_redirects,246 cert=cert,247 verify=verify,
8 unmodified lines
256 params: typing.Optional[QueryParamTypes] = None,257 headers: typing.Optional[HeaderTypes] = None,258 cookies: typing.Optional[CookieTypes] = None,259 auth: typing.Optional[AuthTypes] = None,260 proxy: typing.Optional[ProxyTypes] = None,261 proxies: typing.Optional[ProxiesTypes] = None,262 follow_redirects: bool = False,263 cert: typing.Optional[CertTypes] = None,264 verify: VerifyTypes = True,
14 unmodified lines
279 params=params,280 headers=headers,281 cookies=cookies,282 auth=auth,283 proxy=proxy,284 proxies=proxies,285 follow_redirects=follow_redirects,286 cert=cert,287 verify=verify,
12 unmodified lines
300 params: typing.Optional[QueryParamTypes] = None,301 headers: typing.Optional[HeaderTypes] = None,302 cookies: typing.Optional[CookieTypes] = None,303 auth: typing.Optional[AuthTypes] = None,304 proxy: typing.Optional[ProxyTypes] = None,305 proxies: typing.Optional[ProxiesTypes] = None,306 follow_redirects: bool = False,307 cert: typing.Optional[CertTypes] = None,308 verify: VerifyTypes = True,
15 unmodified lines
324 params=params,325 headers=headers,326 cookies=cookies,327 auth=auth,328 proxy=proxy,329 proxies=proxies,330 follow_redirects=follow_redirects,331 cert=cert,332 verify=verify,
12 unmodified lines
345 params: typing.Optional[QueryParamTypes] = None,346 headers: typing.Optional[HeaderTypes] = None,347 cookies: typing.Optional[CookieTypes] = None,348 auth: typing.Optional[AuthTypes] = None,349 proxy: typing.Optional[ProxyTypes] = None,350 proxies: typing.Optional[ProxiesTypes] = None,351 follow_redirects: bool = False,352 cert: typing.Optional[CertTypes] = None,353 verify: VerifyTypes = True,
15 unmodified lines
369 params=params,370 headers=headers,371 cookies=cookies,372 auth=auth,373 proxy=proxy,374 proxies=proxies,375 follow_redirects=follow_redirects,376 cert=cert,377 verify=verify,
12 unmodified lines
390 params: typing.Optional[QueryParamTypes] = None,391 headers: typing.Optional[HeaderTypes] = None,392 cookies: typing.Optional[CookieTypes] = None,393 auth: typing.Optional[AuthTypes] = None,394 proxy: typing.Optional[ProxyTypes] = None,395 proxies: typing.Optional[ProxiesTypes] = None,396 follow_redirects: bool = False,397 cert: typing.Optional[CertTypes] = None,398 verify: VerifyTypes = True,
15 unmodified lines
414 params=params,415 headers=headers,416 cookies=cookies,417 auth=auth,418 proxy=proxy,419 proxies=proxies,420 follow_redirects=follow_redirects,421 cert=cert,422 verify=verify,
8 unmodified lines
431 params: typing.Optional[QueryParamTypes] = None,432 headers: typing.Optional[HeaderTypes] = None,433 cookies: typing.Optional[CookieTypes] = None,434 auth: typing.Optional[AuthTypes] = None,435 proxy: typing.Optional[ProxyTypes] = None,436 proxies: typing.Optional[ProxiesTypes] = None,437 follow_redirects: bool = False,438 cert: typing.Optional[CertTypes] = None,439 verify: VerifyTypes = True,
14 unmodified lines
454 params=params,455 headers=headers,456 cookies=cookies,457 auth=auth,458 proxy=proxy,459 proxies=proxies,460 follow_redirects=follow_redirects,461 cert=cert,462 verify=verify,
3 unmodified lines
modified:httpx/_client.py+31 added-4 removed
34 unmodified lines
35 CertTypes,36 CookieTypes,37 HeaderTypes,38 ProxiesTypes,39 ProxyTypes,40 QueryParamTypes,41 RequestContent,42 RequestData,43 RequestExtensions,
553 unmodified lines
597 * **cert** - *(optional)* An SSL certificate used by the requested host598 to authenticate the client. Either a path to an SSL certificate file, or599 two-tuple of (certificate file, key file), or a three-tuple of (certificate600 file, key file, password).601 * **proxy** - *(optional)* A proxy URL where all the traffic should be routed.602 * **proxies** - *(optional)* A dictionary mapping proxy keys to proxy603 URLs.604 * **timeout** - *(optional)* The timeout configuration to use when sending605 requests.
23 unmodified lines
629 verify: VerifyTypes = True,630 cert: typing.Optional[CertTypes] = None,631 http1: bool = True,632 http2: bool = False,633 proxy: typing.Optional[ProxyTypes] = None,634 proxies: typing.Optional[ProxiesTypes] = None,632 mounts: typing.Optional[typing.Mapping[str, BaseTransport]] = None,635 mounts: typing.Optional[636 typing.Mapping[str, typing.Optional[BaseTransport]]637 ] = None,638 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,639 follow_redirects: bool = False,640 limits: Limits = DEFAULT_LIMITS,641 max_redirects: int = DEFAULT_MAX_REDIRECTS,
28 unmodified lines
670 "Using http2=True, but the 'h2' package is not installed. "671 "Make sure to install httpx using `pip install httpx[http2]`."672 ) from None673674 if proxies:675 message = (676 "The 'proxies' argument is now deprecated."677 " Use 'proxy' or 'mounts' instead."678 )679 warnings.warn(message, DeprecationWarning)680 if proxy:681 raise RuntimeError("Use either `proxy` or 'proxies', not both.")682683 allow_env_proxies = trust_env and app is None and transport is None670 proxy_map = self._get_proxy_map(proxies, allow_env_proxies)684 proxy_map = self._get_proxy_map(proxies or proxy, allow_env_proxies)685686 self._transport = self._init_transport(687 verify=verify,688 cert=cert,
648 unmodified lines
1337 two-tuple of (certificate file, key file), or a three-tuple of (certificate1338 file, key file, password).1339 * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be1340 enabled. Defaults to `False`.1341 * **proxy** - *(optional)* A proxy URL where all the traffic should be routed.1342 * **proxies** - *(optional)* A dictionary mapping HTTP protocols to proxy1343 URLs.1344 * **timeout** - *(optional)* The timeout configuration to use when sending1345 requests.
23 unmodified lines
1369 verify: VerifyTypes = True,1370 cert: typing.Optional[CertTypes] = None,1371 http1: bool = True,1372 http2: bool = False,1373 proxy: typing.Optional[ProxyTypes] = None,1374 proxies: typing.Optional[ProxiesTypes] = None,1359 mounts: typing.Optional[typing.Mapping[str, AsyncBaseTransport]] = None,1375 mounts: typing.Optional[1376 typing.Mapping[str, typing.Optional[AsyncBaseTransport]]1377 ] = None,1378 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,1379 follow_redirects: bool = False,1380 limits: Limits = DEFAULT_LIMITS,1381 max_redirects: int = DEFAULT_MAX_REDIRECTS,
28 unmodified lines
1410 "Using http2=True, but the 'h2' package is not installed. "1411 "Make sure to install httpx using `pip install httpx[http2]`."1412 ) from None14131414 if proxies:1415 message = (1416 "The 'proxies' argument is now deprecated."1417 " Use 'proxy' or 'mounts' instead."1418 )1419 warnings.warn(message, DeprecationWarning)1420 if proxy:1421 raise RuntimeError("Use either `proxy` or 'proxies', not both.")14221423 allow_env_proxies = trust_env and app is None and transport is None1397 proxy_map = self._get_proxy_map(proxies, allow_env_proxies)1424 proxy_map = self._get_proxy_map(proxies or proxy, allow_env_proxies)14251426 self._transport = self._init_transport(1427 verify=verify,1428 cert=cert,
609 unmodified lines
modified:httpx/_main.py+5 added-5 removed
68 unmodified lines
69 " in a trivially reversible format.",70 )7172 table.add_row(73 "--proxies [cyan]URL",73 "--proxy [cyan]URL",74 "Send the request via a proxy. Should be the URL giving the proxy address.",75 )7677 table.add_row(
307 unmodified lines
385 "including the password encoding in a trivially reversible format."386 ),387)388@click.option(389 "--proxies",390 "proxies",389 "--proxy",390 "proxy",391 type=str,392 default=None,393 help="Send the request via a proxy. Should be the URL giving the proxy address.",394)
60 unmodified lines
455 json: str,456 headers: typing.List[typing.Tuple[str, str]],457 cookies: typing.List[typing.Tuple[str, str]],458 auth: typing.Optional[typing.Tuple[str, str]],459 proxies: str,459 proxy: str,460 timeout: float,461 follow_redirects: bool,462 verify: bool,463 http2: bool,
8 unmodified lines
472 method = "POST" if content or data or files or json else "GET"473474 try:475 with Client(476 proxies=proxies,476 proxy=proxy,477 timeout=timeout,478 verify=verify,479 http2=http2,480 ) as client:
27 unmodified lines
modified:httpx/_types.py+2 added-1 removed
76 unmodified lines
77 Optional[float],78 Tuple[Optional[float], Optional[float], Optional[float], Optional[float]],79 "Timeout",80]81ProxiesTypes = Union[URLTypes, "Proxy", Dict[URLTypes, Union[None, URLTypes, "Proxy"]]]81ProxyTypes = Union[URLTypes, "Proxy"]82ProxiesTypes = Union[ProxyTypes, Dict[URLTypes, Union[None, ProxyTypes]]]8384AuthTypes = Union[85 Tuple[Union[str, bytes], Union[str, bytes]],86 Callable[["Request"], "Request"],
48 unmodified lines
modified:tests/client/test_proxies.py+63 added-11 removed
31 unmodified lines
32 ),33 ],34)35def test_proxies_parameter(proxies, expected_proxies):36 with pytest.warns(DeprecationWarning):36 client = httpx.Client(proxies=proxies)37 client = httpx.Client(proxies=proxies)38 client_patterns = [p.pattern for p in client._mounts.keys()]39 client_proxies = list(client._mounts.values())4041 for proxy_key, url in expected_proxies:
5 unmodified lines
4748 assert len(expected_proxies) == len(client._mounts)495051def test_socks_proxy_deprecated():52 url = httpx.URL("http://www.example.com")5354 with pytest.warns(DeprecationWarning):55 client = httpx.Client(proxies="socks5://localhost/")56 transport = client._transport_for_url(url)57 assert isinstance(transport, httpx.HTTPTransport)58 assert isinstance(transport._pool, httpcore.SOCKSProxy)5960 with pytest.warns(DeprecationWarning):61 async_client = httpx.AsyncClient(proxies="socks5://localhost/")62 async_transport = async_client._transport_for_url(url)63 assert isinstance(async_transport, httpx.AsyncHTTPTransport)64 assert isinstance(async_transport._pool, httpcore.AsyncSOCKSProxy)656667def test_socks_proxy():68 url = httpx.URL("http://www.example.com")6953 client = httpx.Client(proxies="socks5://localhost/")70 client = httpx.Client(proxy="socks5://localhost/")71 transport = client._transport_for_url(url)72 assert isinstance(transport, httpx.HTTPTransport)73 assert isinstance(transport._pool, httpcore.SOCKSProxy)7458 async_client = httpx.AsyncClient(proxies="socks5://localhost/")75 async_client = httpx.AsyncClient(proxy="socks5://localhost/")76 async_transport = async_client._transport_for_url(url)77 assert isinstance(async_transport, httpx.AsyncHTTPTransport)78 assert isinstance(async_transport._pool, httpcore.AsyncSOCKSProxy)79
57 unmodified lines
137 ),138 ],139)140def test_transport_for_request(url, proxies, expected):141 if proxies:142 with pytest.warns(DeprecationWarning):124 client = httpx.Client(proxies=proxies)143 client = httpx.Client(proxies=proxies)144 else:145 client = httpx.Client(proxies=proxies)146147 transport = client._transport_for_url(httpx.URL(url))148149 if expected is None:150 assert transport is client._transport
6 unmodified lines
157@pytest.mark.anyio158@pytest.mark.network159async def test_async_proxy_close():160 try:161 with pytest.warns(DeprecationWarning):139 client = httpx.AsyncClient(proxies={"https://": PROXY_URL})162 client = httpx.AsyncClient(proxies={"https://": PROXY_URL})163 await client.get("http://example.com")164 finally:165 await client.aclose()166167168@pytest.mark.network169def test_sync_proxy_close():170 try:171 with pytest.warns(DeprecationWarning):148 client = httpx.Client(proxies={"https://": PROXY_URL})172 client = httpx.Client(proxies={"https://": PROXY_URL})173 client.get("http://example.com")174 finally:175 client.close()176177178def test_unsupported_proxy_scheme_deprecated():179 with pytest.warns(DeprecationWarning), pytest.raises(ValueError):180 httpx.Client(proxies="ftp://127.0.0.1")181182183def test_unsupported_proxy_scheme():184 with pytest.raises(ValueError):156 httpx.Client(proxies="ftp://127.0.0.1")185 httpx.Client(proxy="ftp://127.0.0.1")186187188@pytest.mark.parametrize(189 ["url", "env", "expected"],
117 unmodified lines
307 ({"all://": "http://127.0.0.1"}, True),308 ],309)310def test_for_deprecated_proxy_params(proxies, is_valid):311 with pytest.warns(DeprecationWarning):282 if not is_valid:283 with pytest.raises(ValueError):312 if not is_valid:313 with pytest.raises(ValueError):314 httpx.Client(proxies=proxies)315 else:316 httpx.Client(proxies=proxies)285 else:286 httpx.Client(proxies=proxies)317318319def test_proxy_and_proxies_together():320 with pytest.warns(DeprecationWarning), pytest.raises(321 RuntimeError,322 ):323 httpx.Client(proxies={"all://": "http://127.0.0.1"}, proxy="http://127.0.0.1")324325 with pytest.warns(DeprecationWarning), pytest.raises(326 RuntimeError,327 ):328 httpx.AsyncClient(329 proxies={"all://": "http://127.0.0.1"}, proxy="http://127.0.0.1"330 )331332333def test_proxy_with_mounts():334 proxy_transport = httpx.HTTPTransport(proxy="http://127.0.0.1")335 client = httpx.Client(mounts={"http://": proxy_transport})336337 transport = client._transport_for_url(httpx.URL("http://example.com"))338 assert transport == proxy_transport
modified:CHANGELOG.md+4 added
4 unmodified lines
5The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).67## Unreleased89### Changed1011* The `proxies` argument is now deprecated. You should use the `proxy` argument instead, or use `mounts=` for more complex configurations. (#2879)1213### Fixed1415* Allow URLs where username or password contains unescaped '@'. (#2986)16
1048 unmodified lines