Skip to content
Myr

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

4 files+145 added−40 removed

modified:httpx/_client.py+11 added-34 removed
42 unmodified lines
43 VerifyTypes,44)45from ._utils import (46 NetRCInfo,47 URLMatcher,48 enforce_http_url,49 get_environment_proxies,50 get_logger,51 same_origin,
419 unmodified lines
471 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 line
482 trust_env=trust_env,483 )484 for key, proxy in proxy_map.items()485 }486 self._proxies = dict(sorted(self._proxies.items()))487488 def _init_transport(489 self,490 verify: VerifyTypes = True,
49 unmodified lines
540 """541 enforce_http_url(url)542543 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 transport547548 return self._transport549
438 unmodified lines
988 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 line
999 trust_env=trust_env,1000 )1001 for key, proxy in proxy_map.items()1002 }1003 self._proxies = dict(sorted(self._proxies.items()))10041005 def _init_transport(1006 self,1007 verify: VerifyTypes = True,
49 unmodified lines
1057 """1058 enforce_http_url(url)10591060 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 transport10641065 return self._transport1066
411 unmodified lines
modified:httpx/_utils.py+84 added
427 unmodified lines
428 return timedelta(seconds=perf_counter() - self.start)429 return timedelta(seconds=self.end - self.start)430431432class URLMatcher:433 """434 A utility class currently used for making lookups against proxy keys...435436 # Wildcard matching...437 >>> pattern = URLMatcher("all")438 >>> pattern.matches(httpx.URL("http://example.com"))439 True440441 # 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 False447448 # 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 False456457 # 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 False465466 # 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 """473474 def __init__(self, pattern: str) -> None:475 from ._models import URL476477 if pattern and ":" not in pattern:478 pattern += "://"479480 url = URL(pattern)481 self.pattern = pattern482 self.scheme = "" if url.scheme == "all" else url.scheme483 self.host = url.host484 self.port = url.port485486 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 True494495 @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)505506 def __hash__(self) -> int:507 return hash(self.pattern)508509 def __lt__(self, other: "URLMatcher") -> bool:510 return self.priority < other.priority511512 def __eq__(self, other: typing.Any) -> bool:513 return isinstance(other, URLMatcher) and self.pattern == other.pattern514515516def warn_deprecated(message: str) -> None: # pragma: nocover517 warnings.warn(message, DeprecationWarning, stacklevel=2)
modified:tests/client/test_proxies.py+8 added-6 removed
1import httpcore2import pytest34import httpx5from httpx._utils import URLMatcher678def url_to_origin(url: str):9 """
26 unmodified lines
36def test_proxies_parameter(proxies, expected_proxies):37 client = httpx.AsyncClient(proxies=proxies)3839 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)4546 assert len(expected_proxies) == len(client._proxies)
8 unmodified lines
55 ("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 lines
modified:tests/test_utils.py+42 added
1import asyncio2import os3import random45import pytest67import httpx8from 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 lines
308def 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)312313314@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)333def test_url_matches(pattern, url, expected):334 matcher = URLMatcher(pattern)335 assert matcher.matches(httpx.URL(url)) == expected336337338def 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 ]