Drop `URL(allow_relative=bool)` (#1073)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Drop URL(allow_relative=bool) * Update httpx/_models.py Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * Linting
authored by Tom Christie · committed by GitHub · parent 083d2e9 · Browse files · 7 files·+38 added−38 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
7 files+38 added−38 removed
- tests:+15 added−12 removed
- other:+23 added−26 removed
Provenance
- Commit
7e6e351- Tree
cd9833d- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
083d2e9
7 files changed+38 added−38 removed
modified:httpx/_client.py+7 added-7 removed
42 unmodified lines43 VerifyTypes,44 )45 from ._utils import (46 NetRCInfo,47+ enforce_http_url,48 get_environment_proxies,49 get_logger,50 same_origin,51 should_not_be_proxied,17 unmodified lines69 base_url: URLTypes = None,70 trust_env: bool = True,71 ):72 if base_url is None:72- self.base_url = URL("", allow_relative=True)73+ self.base_url = URL("")74 else:75 self.base_url = URL(base_url)76 77 self.auth = auth240 unmodified lines318 Return the URL for the redirect to follow.319 """320 location = response.headers["Location"]321 321- url = URL(location, allow_relative=True)322+ url = URL(location)323 324 # Check that we can handle the scheme325 if url.scheme and url.scheme not in ("http", "https"):326 raise InvalidURL(f'Scheme "{url.scheme}" not supported.')212 unmodified lines539 """540 Returns the transport instance that should be used for a given URL.541 This will either be the standard connection pool, or a proxy.542 """543+ enforce_http_url(url)544+545 if self._proxies and not should_not_be_proxied(url):546 is_default_port = (url.scheme == "http" and url.port == 80) or (547 url.scheme == "https" and url.port == 443548 )143 unmodified lines692 def _send_single_request(self, request: Request, timeout: Timeout) -> Response:693 """694 Sends a single request, without handling any redirections.695 """693-696 transport = self._transport_for_url(request.url)697 698 with map_exceptions(HTTPCORE_EXC_MAP, request=request):699 (372 unmodified lines1072 """1073 Returns the transport instance that should be used for a given URL.1074 This will either be the standard connection pool, or a proxy.1075 """1076+ enforce_http_url(url)1077+1078 if self._proxies and not should_not_be_proxied(url):1079 is_default_port = (url.scheme == "http" and url.port == 80) or (1080 url.scheme == "https" and url.port == 4431081 )51 unmodified lines1133 auth: AuthTypes = None,1134 allow_redirects: bool = True,1135 timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET,1136 ) -> Response:1133- if request.url.scheme not in ("http", "https"):1134- raise InvalidURL('URL scheme must be "http" or "https".')1135-1137 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)1138 1139 auth = self._build_auth(request, auth)1140 84 unmodified lines1225 ) -> Response:1226 """1227 Sends a single request, without handling any redirections.1228 """1228-1229 transport = self._transport_for_url(request.url)1230 1231 with map_exceptions(HTTPCORE_EXC_MAP, request=request):1232 (276 unmodified linesmodified:httpx/_models.py+3 added-19 removed
22 unmodified lines23 )24 from ._exceptions import (25 CookieConflict,26 HTTPStatusError,27- InvalidURL,27 NotRedirectResponse,28 RequestNotRead,29 ResponseClosed,30 ResponseNotRead,22 unmodified lines53 )54 55 56 class URL:58- def __init__(59- self,60- url: URLTypes,61- allow_relative: bool = False,62- params: QueryParamTypes = None,63- ) -> None:57+ def __init__(self, url: URLTypes, params: QueryParamTypes = None) -> None:58 if isinstance(url, str):59 self._uri_reference = rfc3986.api.iri_reference(url).encode()60 else:61 self._uri_reference = url._uri_reference11 unmodified lines73 else:74 query_string = str(QueryParams(params))75 self._uri_reference = self._uri_reference.copy_with(query=query_string)76 83- # Enforce absolute URLs by default.84- if not allow_relative:85- if not self.scheme:86- raise InvalidURL("No scheme included in URL.")87- if not self.host:88- raise InvalidURL("No host included in URL.")89-77 @property78 def scheme(self) -> str:79 return self._uri_reference.scheme or ""80 100 unmodified lines181 authority = f"{userpass}@{authority}"182 183 kwargs["authority"] = authority184 198- return URL(199- self._uri_reference.copy_with(**kwargs).unsplit(),200- allow_relative=self.is_relative_url,201- )185+ return URL(self._uri_reference.copy_with(**kwargs).unsplit(),)186 187 def join(self, relative_url: URLTypes) -> "URL":188 """189 Return an absolute URL, using given this URL as the base.3 unmodified lines193 194 # We drop any fragment portion, because RFC 3986 strictly195 # treats URLs with a fragment portion as not being absolute URLs.196 base_uri = self._uri_reference.copy_with(fragment=None)213- relative_url = URL(relative_url, allow_relative=True)197+ relative_url = URL(relative_url)198 return URL(relative_url._uri_reference.resolve_with(base_uri).unsplit())199 200 def __hash__(self) -> int:201 return hash(str(self))936 unmodified linesmodified:httpx/_utils.py+13 added
12 unmodified lines13 from time import perf_counter14 from types import TracebackType15 from urllib.request import getproxies16 17+from ._exceptions import InvalidURL18 from ._types import PrimitiveData19 20 if typing.TYPE_CHECKING: # pragma: no cover21 from ._models import URL238 unmodified lines260 261 return typing.cast(Logger, logger)262 263 264+def enforce_http_url(url: "URL") -> None:265+ """266+ Raise an appropriate InvalidURL for any non-HTTP URLs.267+ """268+ if not url.scheme:269+ raise InvalidURL("No scheme included in URL.")270+ if not url.host:271+ raise InvalidURL("No host included in URL.")272+ if url.scheme not in ("http", "https"):273+ raise InvalidURL('URL scheme must be "http" or "https".')274+275+276 def same_origin(url: "URL", other: "URL") -> bool:277 """278 Return 'True' if the given URLs share the same origin.279 """142 unmodified linesmodified:tests/client/test_async_client.py+4 added
21 unmodified lines22 async def test_get_invalid_url(server):23 async with httpx.AsyncClient() as client:24 with pytest.raises(httpx.InvalidURL):25 await client.get("invalid://example.org")26+ with pytest.raises(httpx.InvalidURL):27+ await client.get("://example.org")28+ with pytest.raises(httpx.InvalidURL):29+ await client.get("http://")30 31 32 @pytest.mark.usefixtures("async_environment")33 async def test_build_request(server):128 unmodified linesmodified:tests/client/test_client.py+10 added
20 unmodified lines21 assert repr(response) == "<Response [200 OK]>"22 assert response.elapsed > timedelta(0)23 24 25+def test_get_invalid_url(server):26+ with httpx.Client() as client:27+ with pytest.raises(httpx.InvalidURL):28+ client.get("invalid://example.org")29+ with pytest.raises(httpx.InvalidURL):30+ client.get("://example.org")31+ with pytest.raises(httpx.InvalidURL):32+ client.get("http://")33+34+35 def test_build_request(server):36 url = server.url.copy_with(path="/echo_headers")37 headers = {"Custom-header": "value"}38 151 unmodified linesmodified:tests/models/test_requests.py-8 removed
108 unmodified lines109 request = httpx.Request("GET", url)110 assert request.url.scheme == "https"111 assert request.url.port == 443112 assert request.url.full_path == "/abc?foo=bar"113-114-115-def test_invalid_urls():116- with pytest.raises(httpx.InvalidURL):117- httpx.Request("GET", "example.org")118-119- with pytest.raises(httpx.InvalidURL):120- httpx.Request("GET", "http:///foo")modified:tests/models/test_url.py+1 added-4 removed
1 import pytest2 3-from httpx import URL, InvalidURL3+from httpx import URL4 5 6 @pytest.mark.parametrize(7 "given,idna,host,scheme,port",107 unmodified lines115 """116 117 url = URL("http://example.com/b/c/d;p?q")118 119- with pytest.raises(InvalidURL):120- assert url.join("g:h") == "g:h"121-119 assert url.join("g") == "http://example.com/b/c/g"120 assert url.join("./g") == "http://example.com/b/c/g"121 assert url.join("g/") == "http://example.com/b/c/g/"122 assert url.join("/g") == "http://example.com/g"65 unmodified lines