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 ---------
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
Provenance
- Commit
f8981f3- Tree
931ff2a- Author
Kar Petrosyan <92274156+karpetrosyan@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
b471f01
11 files changed+281 added−170 removed
modified:docs/advanced.md+132 added-132 removed
502 unmodified lines503 The `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.504 505 ## HTTP Proxying506 507-HTTPX 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=...)`.507+HTTPX 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=...)`.508 509 <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 lines515 516 To route all traffic (HTTP and HTTPS) to a proxy located at `http://localhost:8030`, pass the proxy URL to the client...517 518 ```python519-with httpx.Client(proxies="http://localhost:8030") as client:519+with httpx.Client(proxy="http://localhost:8030") as client:520 ...521 ```522 523-For 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:523+For 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:524 525 ```python526-proxies = {527- "http://": "http://localhost:8030",528- "https://": "http://localhost:8031",526+proxy_mounts = {527+ "http://": httpx.HTTPTransport(proxy="http://localhost:8030"),528+ "https://": httpx.HTTPTransport(proxy="http://localhost:8031"),529 }530 531-with httpx.Client(proxies=proxies) as client:531+with httpx.Client(mounts=proxy_mounts) as client:532 ...533 ```534 535 For detailed information about proxy routing, see the [Routing](#routing) section.9 unmodified lines545 546 Proxy credentials can be passed as the `userinfo` section of the proxy URL. For example:547 548 ```python549-proxies = {550- "http://": "http://username:password@localhost:8030",551- # ...552-}549+with httpx.Client(proxy="http://username:password@localhost:8030") as client:550+ ...551 ```552 555-### Routing556-557-HTTPX provides fine-grained controls for deciding which requests should go through a proxy, and which shouldn't. This process is known as proxy routing.558-559-The `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://`).560-561-HTTPX supports routing proxies based on **scheme**, **domain**, **port**, or a combination of these.562-563-#### Wildcard routing564-565-Route everything through a proxy...566-567-```python568-proxies = {569- "all://": "http://localhost:8030",570-}571-```572-573-#### Scheme routing574-575-Route HTTP requests through one proxy, and HTTPS requests through another...576-577-```python578-proxies = {579- "http://": "http://localhost:8030",580- "https://": "http://localhost:8031",581-}582-```583-584-#### Domain routing585-586-Proxy all requests on domain "example.com", let other requests pass through...587-588-```python589-proxies = {590- "all://example.com": "http://localhost:8030",591-}592-```593-594-Proxy HTTP requests on domain "example.com", let HTTPS and other requests pass through...595-596-```python597-proxies = {598- "http://example.com": "http://localhost:8030",599-}600-```601-602-Proxy all requests to "example.com" and its subdomains, let other requests pass through...603-604-```python605-proxies = {606- "all://*example.com": "http://localhost:8030",607-}608-```609-610-Proxy all requests to strict subdomains of "example.com", let "example.com" and other requests pass through...611-612-```python613-proxies = {614- "all://*.example.com": "http://localhost:8030",615-}616-```617-618-#### Port routing619-620-Proxy HTTPS requests on port 1234 to "example.com"...621-622-```python623-proxies = {624- "https://example.com:1234": "http://localhost:8030",625-}626-```627-628-Proxy all requests on port 1234...629-630-```python631-proxies = {632- "all://*:1234": "http://localhost:8030",633-}634-```635-636-#### No-proxy support637-638-It is also possible to define requests that _shouldn't_ be routed through proxies.639-640-To do so, pass `None` as the proxy URL. For example...641-642-```python643-proxies = {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-```650-651-#### Complex configuration example652-653-You can combine the routing features outlined above to build complex proxy routing configurations. For example...654-655-```python656-proxies = {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-```668-669-#### Environment variables670-671-HTTP proxying can also be configured through environment variables, although with less fine-grained control.672-673-See documentation on [`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`](environment_variables.md#http_proxy-https_proxy-all_proxy) for more information.674-553 ### Proxy mechanisms554 555 !!! note556 This section describes **advanced** proxy concepts and functionality.27 unmodified lines584 585 You can now configure a client to make requests via a proxy using the SOCKS protocol:586 587 ```python710-httpx.Client(proxies='socks5://user:pass@host:port')588+httpx.Client(proxy='socks5://user:pass@host:port')589 ```590 591 ## Timeout Configuration592 578 unmodified lines1171 # Support URLs like "file:///Users/sylvia_green/websites/new_client/index.html"1172 mounts = {"file://": FileSystemTransport()}1173 client = httpx.Client(mounts=mounts)1174 ```1175+1176+### Routing1177+1178+HTTPX provides a powerful mechanism for routing requests, allowing you to write complex rules that specify which transport should be used for each request.1179+1180+The `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://`).1181+1182+HTTPX supports routing requests based on **scheme**, **domain**, **port**, or a combination of these.1183+1184+#### Wildcard routing1185+1186+Route everything through a transport...1187+1188+```python1189+mounts = {1190+ "all://": httpx.HTTPTransport(proxy="http://localhost:8030"),1191+}1192+```1193+1194+#### Scheme routing1195+1196+Route HTTP requests through one transport, and HTTPS requests through another...1197+1198+```python1199+mounts = {1200+ "http://": httpx.HTTPTransport(proxy="http://localhost:8030"),1201+ "https://": httpx.HTTPTransport(proxy="http://localhost:8031"),1202+}1203+```1204+1205+#### Domain routing1206+1207+Proxy all requests on domain "example.com", let other requests pass through...1208+1209+```python1210+mounts = {1211+ "all://example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),1212+}1213+```1214+1215+Proxy HTTP requests on domain "example.com", let HTTPS and other requests pass through...1216+1217+```python1218+mounts = {1219+ "http://example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),1220+}1221+```1222+1223+Proxy all requests to "example.com" and its subdomains, let other requests pass through...1224+1225+```python1226+mounts = {1227+ "all://*example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),1228+}1229+```1230+1231+Proxy all requests to strict subdomains of "example.com", let "example.com" and other requests pass through...1232+1233+```python1234+mounts = {1235+ "all://*.example.com": httpx.HTTPTransport(proxy="http://localhost:8030"),1236+}1237+```1238+1239+#### Port routing1240+1241+Proxy HTTPS requests on port 1234 to "example.com"...1242+1243+```python1244+mounts = {1245+ "https://example.com:1234": httpx.HTTPTransport(proxy="http://localhost:8030"),1246+}1247+```1248+1249+Proxy all requests on port 1234...1250+1251+```python1252+mounts = {1253+ "all://*:1234": httpx.HTTPTransport(proxy="http://localhost:8030"),1254+}1255+```1256+1257+#### No-proxy support1258+1259+It is also possible to define requests that _shouldn't_ be routed through the transport.1260+1261+To do so, pass `None` as the proxy URL. For example...1262+1263+```python1264+mounts = {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+```1271+1272+#### Complex configuration example1273+1274+You can combine the routing features outlined above to build complex proxy routing configurations. For example...1275+1276+```python1277+mounts = {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+```1289+1290+#### Environment variables1291+1292+There are also environment variables that can be used to control the dictionary of the client mounts. 1293+They can be used to configure HTTP proxying for clients.1294+1295+See 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 lines156 ```157 158 ## Proxy keys159 160-When using `httpx.Client(proxies={...})` to map to a selection of different proxies, we use full URL schemes, such as `proxies={"http://": ..., "https://": ...}`.160+HTTPX uses the mounts argument for HTTP proxying and transport routing.161+It can do much more than proxies and allows you to configure more than just the proxy route.162+For more detailed documentation, see [Mounting Transports](advanced.md#mounting-transports).163 164+When using `httpx.Client(mounts={...})` to map to a selection of different transports, we use full URL schemes, such as `mounts={"http://": ..., "https://": ...}`.165+166 This is different to the `requests` usage of `proxies={"http": ..., "https": ...}`.167 164-This 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.168+This 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.169 166-Also note that `requests.Session.request(...)` allows a `proxies=...` parameter, whereas `httpx.Client.request(...)` does not.170+Also note that `requests.Session.request(...)` allows a `proxies=...` parameter, whereas `httpx.Client.request(...)` does not allow `mounts=...`.171 172 ## SSL configuration173 174 When 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 lines198 ## Request instantiation199 200 There 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).201 198-Besides, `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).202+Besides, `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).203 204 ## Mocking205 206 If 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 linesmodified:docs/contributing.md+1 added-3 removed
211 unmodified lines212 213 ```214 import httpx215 216-proxies = {"all://": "http://127.0.0.1:8080/"}217-218-with httpx.Client(proxies=proxies, verify="/path/to/client.pem") as client:216+with 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 linesmodified:docs/troubleshooting.md+9 added-7 removed
17 unmodified lines18192021222324222324252627282 unmodified lines31323334353637353637383940414243444445464748495013 unmodified lines17 unmodified lines
**Resolution**: it is likely that you've set up your proxies like this...
```pythonproxies = { "http://": "http://myproxy.org", "https://": "https://myproxy.org",mounts = { "http://": httpx.HTTPTransport(proxy="http://myproxy.org"), "https://": httpx.HTTPTransport(proxy="https://myproxy.org"),}```
Using this setup, you're telling HTTPX to connect to the proxy using HTTP for HTTP requests, and using HTTPS for HTTPS requests.2 unmodified lines
Change the scheme of your HTTPS proxy to `http://...` instead of `https://...`:
```pythonproxies = { "http://": "http://myproxy.org", "https://": "http://myproxy.org",mounts = { "http://": httpx.HTTPTransport(proxy="http://myproxy.org"), "https://": httpx.HTTPTransport(proxy="http://myproxy.org"),}```
This can be simplified to:
```pythonproxies = "http://myproxy.org"proxy = "http://myproxy.org"with httpx.Client(proxy=proxy) as client: ...```
For more information, see [Proxies: FORWARD vs TUNNEL](advanced.md#forward-vs-tunnel).
13 unmodified linesmodified:httpx/_transports/default.py+6 added-3 removed
45 unmodified lines46 WriteError,47 WriteTimeout,48 )49 from .._models import Request, Response50-from .._types import AsyncByteStream, CertTypes, SyncByteStream, VerifyTypes50+from .._types import AsyncByteStream, CertTypes, ProxyTypes, SyncByteStream, VerifyTypes51+from .._urls import URL52 from .base import AsyncBaseTransport, BaseTransport53 54 T = typing.TypeVar("T", bound="HTTPTransport")55 A = typing.TypeVar("A", bound="AsyncHTTPTransport")68 unmodified lines124 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 proxy136 137 if proxy is None:138 self._pool = httpcore.ConnectionPool(139 ssl_context=ssl_context,125 unmodified lines265 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 proxy277 278 if proxy is None:279 self._pool = httpcore.AsyncConnectionPool(280 ssl_context=ssl_context,103 unmodified linesmodified:httpx/_api.py+20 added
8 unmodified lines9 CertTypes,10 CookieTypes,11 HeaderTypes,12 ProxiesTypes,13+ ProxyTypes,14 QueryParamTypes,15 RequestContent,16 RequestData,17 RequestFiles,14 unmodified lines32 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 lines64 * **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 lines93 ```94 """95 with Client(96 cookies=cookies,97+ proxy=proxy,98 proxies=proxies,99 cert=cert,100 verify=verify,101 timeout=timeout,25 unmodified lines127 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 lines147 [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 lines176 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 lines199 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 lines216 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 lines239 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 lines256 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 lines279 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 lines300 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 lines324 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 lines345 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 lines369 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 lines390 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 lines414 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 lines431 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 lines454 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 linesmodified:httpx/_client.py+31 added-4 removed
34 unmodified lines35 CertTypes,36 CookieTypes,37 HeaderTypes,38 ProxiesTypes,39+ ProxyTypes,40 QueryParamTypes,41 RequestContent,42 RequestData,43 RequestExtensions,553 unmodified lines597 * **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 lines629 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 lines670 "Using http2=True, but the 'h2' package is not installed. "671 "Make sure to install httpx using `pip install httpx[http2]`."672 ) from None673 674+ 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.")682+683 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)685 686 self._transport = self._init_transport(687 verify=verify,688 cert=cert,648 unmodified lines1337 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 lines1369 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 lines1410 "Using http2=True, but the 'h2' package is not installed. "1411 "Make sure to install httpx using `pip install httpx[http2]`."1412 ) from None1413 1414+ 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.")1422+1423 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)1425 1426 self._transport = self._init_transport(1427 verify=verify,1428 cert=cert,609 unmodified linesmodified:httpx/_main.py+5 added-5 removed
68 unmodified lines69 " in a trivially reversible format.",70 )71 72 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 )76 77 table.add_row(307 unmodified lines385 "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 lines455 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 lines472 method = "POST" if content or data or files or json else "GET"473 474 try:475 with Client(476- proxies=proxies,476+ proxy=proxy,477 timeout=timeout,478 verify=verify,479 http2=http2,480 ) as client:27 unmodified linesmodified:httpx/_types.py+2 added-1 removed
76 unmodified lines77 Optional[float],78 Tuple[Optional[float], Optional[float], Optional[float], Optional[float]],79 "Timeout",80 ]81-ProxiesTypes = Union[URLTypes, "Proxy", Dict[URLTypes, Union[None, URLTypes, "Proxy"]]]81+ProxyTypes = Union[URLTypes, "Proxy"]82+ProxiesTypes = Union[ProxyTypes, Dict[URLTypes, Union[None, ProxyTypes]]]83 84 AuthTypes = Union[85 Tuple[Union[str, bytes], Union[str, bytes]],86 Callable[["Request"], "Request"],48 unmodified linesmodified:tests/client/test_proxies.py+63 added-11 removed
31 unmodified lines32 ),33 ],34 )35 def 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())40 41 for proxy_key, url in expected_proxies:5 unmodified lines47 48 assert len(expected_proxies) == len(client._mounts)49 50 51+def test_socks_proxy_deprecated():52+ url = httpx.URL("http://www.example.com")53+54+ 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)59+60+ 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)65+66+67 def test_socks_proxy():68 url = httpx.URL("http://www.example.com")69 53- 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)74 58- 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 lines137 ),138 ],139 )140 def 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)146+147 transport = client._transport_for_url(httpx.URL(url))148 149 if expected is None:150 assert transport is client._transport6 unmodified lines157 @pytest.mark.anyio158 @pytest.mark.network159 async 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()166 167 168 @pytest.mark.network169 def 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()176 177 178+def test_unsupported_proxy_scheme_deprecated():179+ with pytest.warns(DeprecationWarning), pytest.raises(ValueError):180+ httpx.Client(proxies="ftp://127.0.0.1")181+182+183 def 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")186 187 188 @pytest.mark.parametrize(189 ["url", "env", "expected"],117 unmodified lines307 ({"all://": "http://127.0.0.1"}, True),308 ],309 )310 def 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)317+318+319+def 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")324+325+ 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+ )331+332+333+def test_proxy_with_mounts():334+ proxy_transport = httpx.HTTPTransport(proxy="http://127.0.0.1")335+ client = httpx.Client(mounts={"http://": proxy_transport})336+337+ transport = client._transport_for_url(httpx.URL("http://example.com"))338+ assert transport == proxy_transportmodified:CHANGELOG.md+4 added
4 unmodified lines5 The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).6 7 ## Unreleased8 9+### Changed10+11+* The `proxies` argument is now deprecated. You should use the `proxy` argument instead, or use `mounts=` for more complex configurations. (#2879)12+13 ### Fixed14 15 * Allow URLs where username or password contains unescaped '@'. (#2986)16 1048 unmodified lines