URL matching (#1098)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add internal URLMatcher class * Use URLMatcher for proxy lookups in transport_for_url * Docstring * Pin pytest * Update httpx/_utils.py Co-authored-by: Florimond Manca <florimond.manca@gmail.com>
authored by Tom Christie · committed by GitHub · parent 9728d89 · Browse files · 4 files·+145 added−40 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: Florimond Manca <florimond.manca@gmail.com>
Diff stats
4 files+145 added−40 removed
- tests:+50 added−6 removed
- other:+95 added−34 removed
Provenance
- Commit
df54890- Tree
583286b- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
9728d89
4 files changed+145 added−40 removed
modified:httpx/_client.py+11 added-34 removed
42 unmodified lines43 VerifyTypes,44 )45 from ._utils import (46 NetRCInfo,47+ URLMatcher,48 enforce_http_url,49 get_environment_proxies,50 get_logger,51 same_origin,419 unmodified lines471 transport=transport,472 app=app,473 trust_env=trust_env,474 )474- self._proxies: typing.Dict[str, httpcore.SyncHTTPTransport] = {475- key: self._init_proxy_transport(475+ self._proxies: typing.Dict[URLMatcher, httpcore.SyncHTTPTransport] = {476+ URLMatcher(key): self._init_proxy_transport(477 proxy,478 verify=verify,479 cert=cert,480 http2=http2,1 unmodified line482 trust_env=trust_env,483 )484 for key, proxy in proxy_map.items()485 }486+ self._proxies = dict(sorted(self._proxies.items()))487 488 def _init_transport(489 self,490 verify: VerifyTypes = True,49 unmodified lines540 """541 enforce_http_url(url)542 543 if self._proxies and not should_not_be_proxied(url):542- default_port = {"http": 80, "https": 443}[url.scheme]543- is_default_port = url.port is None or url.port == default_port544- port = url.port or default_port545- hostname = f"{url.host}:{port}"546- proxy_keys = (547- f"{url.scheme}://{hostname}",548- f"{url.scheme}://{url.host}" if is_default_port else None,549- f"all://{hostname}",550- f"all://{url.host}" if is_default_port else None,551- url.scheme,552- "all",553- )554- for proxy_key in proxy_keys:555- if proxy_key and proxy_key in self._proxies:556- transport = self._proxies[proxy_key]544+ for matcher, transport in self._proxies.items():545+ if matcher.matches(url):546 return transport547 548 return self._transport549 438 unmodified lines988 transport=transport,989 app=app,990 trust_env=trust_env,991 )1003- self._proxies: typing.Dict[str, httpcore.AsyncHTTPTransport] = {1004- key: self._init_proxy_transport(992+ self._proxies: typing.Dict[URLMatcher, httpcore.AsyncHTTPTransport] = {993+ URLMatcher(key): self._init_proxy_transport(994 proxy,995 verify=verify,996 cert=cert,997 http2=http2,1 unmodified line999 trust_env=trust_env,1000 )1001 for key, proxy in proxy_map.items()1002 }1003+ self._proxies = dict(sorted(self._proxies.items()))1004 1005 def _init_transport(1006 self,1007 verify: VerifyTypes = True,49 unmodified lines1057 """1058 enforce_http_url(url)1059 1060 if self._proxies and not should_not_be_proxied(url):1071- default_port = {"http": 80, "https": 443}[url.scheme]1072- is_default_port = url.port is None or url.port == default_port1073- port = url.port or default_port1074- hostname = f"{url.host}:{port}"1075- proxy_keys = (1076- f"{url.scheme}://{hostname}",1077- f"{url.scheme}://{url.host}" if is_default_port else None,1078- f"all://{hostname}",1079- f"all://{url.host}" if is_default_port else None,1080- url.scheme,1081- "all",1082- )1083- for proxy_key in proxy_keys:1084- if proxy_key and proxy_key in self._proxies:1085- transport = self._proxies[proxy_key]1061+ for matcher, transport in self._proxies.items():1062+ if matcher.matches(url):1063 return transport1064 1065 return self._transport1066 411 unmodified linesmodified:httpx/_utils.py+84 added
427 unmodified lines428 return timedelta(seconds=perf_counter() - self.start)429 return timedelta(seconds=self.end - self.start)430 431 432+class URLMatcher:433+ """434+ A utility class currently used for making lookups against proxy keys...435+436+ # Wildcard matching...437+ >>> pattern = URLMatcher("all")438+ >>> pattern.matches(httpx.URL("http://example.com"))439+ True440+441+ # Witch scheme matching...442+ >>> pattern = URLMatcher("https")443+ >>> pattern.matches(httpx.URL("https://example.com"))444+ True445+ >>> pattern.matches(httpx.URL("http://example.com"))446+ False447+448+ # With domain matching...449+ >>> pattern = URLMatcher("https://example.com")450+ >>> pattern.matches(httpx.URL("https://example.com"))451+ True452+ >>> pattern.matches(httpx.URL("http://example.com"))453+ False454+ >>> pattern.matches(httpx.URL("https://other.com"))455+ False456+457+ # Wildcard scheme, with domain matching...458+ >>> pattern = URLMatcher("all://example.com")459+ >>> pattern.matches(httpx.URL("https://example.com"))460+ True461+ >>> pattern.matches(httpx.URL("http://example.com"))462+ True463+ >>> pattern.matches(httpx.URL("https://other.com"))464+ False465+466+ # With port matching...467+ >>> pattern = URLMatcher("https://example.com:1234")468+ >>> pattern.matches(httpx.URL("https://example.com:1234"))469+ True470+ >>> pattern.matches(httpx.URL("https://example.com"))471+ False472+ """473+474+ def __init__(self, pattern: str) -> None:475+ from ._models import URL476+477+ if pattern and ":" not in pattern:478+ pattern += "://"479+480+ url = URL(pattern)481+ self.pattern = pattern482+ self.scheme = "" if url.scheme == "all" else url.scheme483+ self.host = url.host484+ self.port = url.port485+486+ def matches(self, other: "URL") -> bool:487+ if self.scheme and self.scheme != other.scheme:488+ return False489+ if self.host and self.host != other.host:490+ return False491+ if self.port is not None and self.port != other.port:492+ return False493+ return True494+495+ @property496+ def priority(self) -> tuple:497+ """498+ The priority allows URLMatcher instances to be sortable, so that499+ we can match from most specific to least specific.500+ """501+ port_priority = -1 if self.port is not None else 0502+ host_priority = -len(self.host)503+ scheme_priority = -len(self.scheme)504+ return (port_priority, host_priority, scheme_priority)505+506+ def __hash__(self) -> int:507+ return hash(self.pattern)508+509+ def __lt__(self, other: "URLMatcher") -> bool:510+ return self.priority < other.priority511+512+ def __eq__(self, other: typing.Any) -> bool:513+ return isinstance(other, URLMatcher) and self.pattern == other.pattern514+515+516 def warn_deprecated(message: str) -> None: # pragma: nocover517 warnings.warn(message, DeprecationWarning, stacklevel=2)modified:tests/client/test_proxies.py+8 added-6 removed
1 import httpcore2 import pytest3 4 import httpx5+from httpx._utils import URLMatcher6 7 8 def url_to_origin(url: str):9 """26 unmodified lines36 def test_proxies_parameter(proxies, expected_proxies):37 client = httpx.AsyncClient(proxies=proxies)38 39 for proxy_key, url in expected_proxies:40+ matcher = URLMatcher(proxy_key)39- assert proxy_key in client._proxies40- proxy = client._proxies[proxy_key]41+ assert matcher in client._proxies42+ proxy = client._proxies[matcher]43 assert isinstance(proxy, httpcore.AsyncHTTPProxy)44 assert proxy.proxy_origin == url_to_origin(url)45 46 assert len(expected_proxies) == len(client._proxies)8 unmodified lines55 ("http://example.com", None, None),56 ("http://example.com", {}, None),57 ("http://example.com", {"https": PROXY_URL}, None),58 ("http://example.com", {"http://example.net": PROXY_URL}, None),57- ("http://example.com:443", {"http://example.com": PROXY_URL}, None),59+ ("http://example.com:443", {"http://example.com": PROXY_URL}, PROXY_URL),60 ("http://example.com", {"all": PROXY_URL}, PROXY_URL),61 ("http://example.com", {"http": PROXY_URL}, PROXY_URL),62 ("http://example.com", {"all://example.com": PROXY_URL}, PROXY_URL),61- ("http://example.com", {"all://example.com:80": PROXY_URL}, PROXY_URL),63+ ("http://example.com", {"all://example.com:80": PROXY_URL}, None),64 ("http://example.com", {"http://example.com": PROXY_URL}, PROXY_URL),63- ("http://example.com", {"http://example.com:80": PROXY_URL}, PROXY_URL),65+ ("http://example.com", {"http://example.com:80": PROXY_URL}, None),66 ("http://example.com:8080", {"http://example.com:8080": PROXY_URL}, PROXY_URL),65- ("http://example.com:8080", {"http://example.com": PROXY_URL}, None),67+ ("http://example.com:8080", {"http://example.com": PROXY_URL}, PROXY_URL),68 (69 "http://example.com",70 {71 "all": PROXY_URL + ":1",77 unmodified linesmodified:tests/test_utils.py+42 added
1 import asyncio2 import os3+import random4 5 import pytest6 7 import httpx8 from httpx._utils import (9 ElapsedTimer,10 NetRCInfo,11+ URLMatcher,12 get_ca_bundle_from_env,13 get_environment_proxies,14 guess_json_utf,15 obfuscate_sensitive_headers,292 unmodified lines308 def test_not_same_origin():309 origin1 = httpx.URL("https://example.com")310 origin2 = httpx.URL("HTTP://EXAMPLE.COM")311 assert not same_origin(origin1, origin2)312+313+314+@pytest.mark.parametrize(315+ ["pattern", "url", "expected"],316+ [317+ ("http://example.com", "http://example.com", True,),318+ ("http://example.com", "https://example.com", False,),319+ ("http://example.com", "http://other.com", False,),320+ ("http://example.com:123", "http://example.com:123", True,),321+ ("http://example.com:123", "http://example.com:456", False,),322+ ("http://example.com:123", "http://example.com", False,),323+ ("all://example.com", "http://example.com", True,),324+ ("all://example.com", "https://example.com", True,),325+ ("http://", "http://example.com", True,),326+ ("http://", "https://example.com", False,),327+ ("http", "http://example.com", True,),328+ ("http", "https://example.com", False,),329+ ("all", "https://example.com:123", True,),330+ ("", "https://example.com:123", True,),331+ ],332+)333+def test_url_matches(pattern, url, expected):334+ matcher = URLMatcher(pattern)335+ assert matcher.matches(httpx.URL(url)) == expected336+337+338+def test_matcher_priority():339+ matchers = [340+ URLMatcher("all://"),341+ URLMatcher("http://"),342+ URLMatcher("http://example.com"),343+ URLMatcher("http://example.com:123"),344+ ]345+ random.shuffle(matchers)346+ assert sorted(matchers) == [347+ URLMatcher("http://example.com:123"),348+ URLMatcher("http://example.com"),349+ URLMatcher("http://"),350+ URLMatcher("all://"),351+ ]