Skip to content
Myr

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

7 files+38 added−38 removed

modified:httpx/_client.py+7 added-7 removed
42 unmodified lines
43 VerifyTypes,44)45from ._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 lines
69 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)7677 self.auth = auth
240 unmodified lines
318 Return the URL for the redirect to follow.319 """320 location = response.headers["Location"]321321 url = URL(location, allow_relative=True)322 url = URL(location)323324 # 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 lines
539 """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)544545 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 lines
692 def _send_single_request(self, request: Request, timeout: Timeout) -> Response:693 """694 Sends a single request, without handling any redirections.695 """693696 transport = self._transport_for_url(request.url)697698 with map_exceptions(HTTPCORE_EXC_MAP, request=request):699 (
372 unmodified lines
1072 """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)10771078 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 lines
1133 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".')11351137 timeout = self.timeout if isinstance(timeout, UnsetType) else Timeout(timeout)11381139 auth = self._build_auth(request, auth)1140
84 unmodified lines
1225 ) -> Response:1226 """1227 Sends a single request, without handling any redirections.1228 """12281229 transport = self._transport_for_url(request.url)12301231 with map_exceptions(HTTPCORE_EXC_MAP, request=request):1232 (
276 unmodified lines
modified:httpx/_models.py+3 added-19 removed
22 unmodified lines
23)24from ._exceptions import (25 CookieConflict,26 HTTPStatusError,27 InvalidURL,27 NotRedirectResponse,28 RequestNotRead,29 ResponseClosed,30 ResponseNotRead,
22 unmodified lines
53)545556class 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_reference
11 unmodified lines
73 else:74 query_string = str(QueryParams(params))75 self._uri_reference = self._uri_reference.copy_with(query=query_string)7683 # 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.")8977 @property78 def scheme(self) -> str:79 return self._uri_reference.scheme or ""80
100 unmodified lines
181 authority = f"{userpass}@{authority}"182183 kwargs["authority"] = authority184198 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(),)186187 def join(self, relative_url: URLTypes) -> "URL":188 """189 Return an absolute URL, using given this URL as the base.
3 unmodified lines
193194 # 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())199200 def __hash__(self) -> int:201 return hash(str(self))
936 unmodified lines
modified:httpx/_utils.py+13 added
12 unmodified lines
13from time import perf_counter14from types import TracebackType15from urllib.request import getproxies1617from ._exceptions import InvalidURL18from ._types import PrimitiveData1920if typing.TYPE_CHECKING: # pragma: no cover21 from ._models import URL
238 unmodified lines
260261 return typing.cast(Logger, logger)262263264def 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".')274275276def same_origin(url: "URL", other: "URL") -> bool:277 """278 Return 'True' if the given URLs share the same origin.279 """
142 unmodified lines
modified:tests/client/test_async_client.py+4 added
21 unmodified lines
22async 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://")303132@pytest.mark.usefixtures("async_environment")33async def test_build_request(server):
128 unmodified lines
modified:tests/client/test_client.py+10 added
20 unmodified lines
21 assert repr(response) == "<Response [200 OK]>"22 assert response.elapsed > timedelta(0)232425def 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://")333435def test_build_request(server):36 url = server.url.copy_with(path="/echo_headers")37 headers = {"Custom-header": "value"}38
151 unmodified lines
modified:tests/models/test_requests.py-8 removed
108 unmodified lines
109 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"113114115def test_invalid_urls():116 with pytest.raises(httpx.InvalidURL):117 httpx.Request("GET", "example.org")118119 with pytest.raises(httpx.InvalidURL):120 httpx.Request("GET", "http:///foo")
modified:tests/models/test_url.py+1 added-4 removed
1import pytest23from httpx import URL, InvalidURL3from httpx import URL456@pytest.mark.parametrize(7 "given,idna,host,scheme,port",
107 unmodified lines
115 """116117 url = URL("http://example.com/b/c/d;p?q")118119 with pytest.raises(InvalidURL):120 assert url.join("g:h") == "g:h"121119 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