Finesse URL properties (#1285)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* url.userinfo should be URL encoded bytes * Neater copy_with implementation * Finesse API around URL properties and copy_with * Docstring for URL, and drop url.authority * Support url.copy_with(raw_path=...) * Docstrings on URL methods * Tweak docstring
authored by Tom Christie · committed by GitHub · parent f3c2941 · Browse files · 5 files·+302 added−52 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+302 added−52 removed
- tests:+85 added−8 removed
- other:+217 added−44 removed
Provenance
- Commit
8e4a8a1- Tree
603ccc7- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
f3c2941
5 files changed+302 added−52 removed
modified:httpx/_auth.py+1 added-1 removed
215 unmodified lines216 return hash_func(data).hexdigest().encode()217 218 A1 = b":".join((self._username, challenge.realm, self._password))219 220- path = request.url.full_path.encode("utf-8")220+ path = request.url.raw_path221 A2 = b":".join((request.method.encode(), path))222 # TODO: implement auth-int223 HA2 = digest(A2)224 88 unmodified linesmodified:httpx/_models.py+214 added-41 removed
60 unmodified lines61 )62 63 64 class URL:65+ """66+ url = httpx.URL("HTTPS://jo%40email.com:a%20secret@example.com:1234/pa%20th?search=ab#anchorlink")67+68+ assert url.scheme == "https"69+ assert url.username == "jo@email.com"70+ assert url.password == "a secret"71+ assert url.userinfo == b"jo%40email.com:a%20secret"72+ assert url.host == "example.com"73+ assert url.port == 123474+ assert url.netloc == "example.com:1234"75+ assert url.path == "/pa th"76+ assert url.query == b"?search=ab"77+ assert url.raw_path == b"/pa%20th?search=ab"78+ assert url.fragment == "anchorlink"79+80+ The components of a URL are broken down like this:81+82+ https://jo%40email.com:a%20secret@example.com:1234/pa%20th?search=ab#anchorlink83+ [scheme][ username ] [password] [ host ][port][ path ] [ query ] [fragment]84+ [ userinfo ] [ netloc ][ raw_path ]85+86+ Note that:87+88+ * `url.scheme` is normalized to always be lowercased.89+90+ * `url.host` is normalized to always be lowercased, and is IDNA encoded. For instance:91+ url = httpx.URL("http://中国.icom.museum")92+ assert url.host == "xn--fiqs8s.icom.museum"93+94+ * `url.userinfo` is raw bytes, without URL escaping. Usually you'll want to work with95+ `url.username` and `url.password` instead, which handle the URL escaping.96+97+ * `url.raw_path` is raw bytes of both the path and query, without URL escaping.98+ This portion is used as the target when constructing HTTP requests. Usually you'll99+ want to work with `url.path` instead.100+101+ * `url.query` is raw bytes, without URL escaping. A URL query string portion can only102+ be properly URL escaped when decoding the parameter names and values themselves.103+ """104+105 def __init__(106 self, url: typing.Union["URL", str, RawURL] = "", params: QueryParamTypes = None107 ) -> None:108 if isinstance(url, (str, tuple)):32 unmodified lines141 self._uri_reference = self._uri_reference.copy_with(query=query_string)142 143 @property144 def scheme(self) -> str:145+ """146+ The URL scheme, such as "http", "https".147+ Always normalised to lowercase.148+ """149 return self._uri_reference.scheme or ""150 151 @property108- def authority(self) -> str:109- port_str = self._uri_reference.port110- default_port_str = {"https": "443", "http": "80"}.get(self.scheme, "")111- if port_str is None or port_str == default_port_str:112- return self._uri_reference.host or ""113- return self._uri_reference.authority or ""152+ def userinfo(self) -> bytes:153+ """154+ The URL userinfo as a raw bytestring.155+ For example: b"jo%40email.com:a%20secret".156+ """157+ userinfo = self._uri_reference.userinfo or ""158+ return userinfo.encode("ascii")159 160 @property116- def userinfo(self) -> str:117- return self._uri_reference.userinfo or ""118-119- @property161 def username(self) -> str:162+ """163+ The URL username as a string, with URL decoding applied.164+ For example: "jo@email.com"165+ """166+ userinfo = self._uri_reference.userinfo or ""121- return unquote(self.userinfo.partition(":")[0])167+ return unquote(userinfo.partition(":")[0])168 169 @property170 def password(self) -> str:171+ """172+ The URL password as a string, with URL decoding applied.173+ For example: "a secret"174+ """175+ userinfo = self._uri_reference.userinfo or ""125- return unquote(self.userinfo.partition(":")[2])176+ return unquote(userinfo.partition(":")[2])177 178 @property179 def host(self) -> str:180+ """181+ The URL host as a string.182+ Always normlized to lowercase, and IDNA encoded.183+184+ Examples:185+186+ url = httpx.URL("http://www.EXAMPLE.org")187+ assert url.host == "www.example.org"188+189+ url = httpx.URL("http://中国.icom.museum")190+ assert url.host == "xn--fiqs8s.icom.museum"191+ """192 return self._uri_reference.host or ""193 194 @property195 def port(self) -> typing.Optional[int]:196+ """197+ The URL port as an integer.198+ """199 port = self._uri_reference.port200 return int(port) if port else None201 202 @property203+ def netloc(self) -> str:204+ """205+ Either `<host>` or `<host>:<port>` as a string.206+ Always normlized to lowercase, and IDNA encoded.207+ """208+ host = self._uri_reference.host or ""209+ port = self._uri_reference.port210+ return host if port is None else f"{host}:{port}"211+212+ @property213 def path(self) -> str:138- return self._uri_reference.path or "/"214+ """215+ The URL path as a string. Excluding the query string, and URL decoded.216 217+ For example:218+219+ url = httpx.URL("https://example.com/pa%20th")220+ assert url.path == "/pa th"221+ """222+ path = self._uri_reference.path or "/"223+ return unquote(path)224+225 @property141- def query(self) -> str:142- return self._uri_reference.query or ""226+ def query(self) -> bytes:227+ """228+ The URL query string, as raw bytes, excluding the leading b"?".229+ Note that URL decoding can only be applied on URL query strings230+ at the point of decoding the individual parameter names/values.231+ """232+ query = self._uri_reference.query or ""233+ return query.encode("ascii")234 235 @property145- def full_path(self) -> str:146- path = self.path147- if self.query:148- path += "?" + self.query149- return path236+ def raw_path(self) -> bytes:237+ """238+ The complete URL path and query string as raw bytes.239+ Used as the target when constructing HTTP requests.240 241+ For example:242+243+ GET /users?search=some%20text HTTP/1.1244+ Host: www.example.org245+ Connection: close246+ """247+ path = self._uri_reference.path or "/"248+ if self._uri_reference.query is not None:249+ path += "?" + self._uri_reference.query250+ return path.encode("ascii")251+252 @property253 def fragment(self) -> str:254+ """255+ The URL fragments, as used in HTML anchors.256+ As a string, without the leading '#'.257+ """258 return self._uri_reference.fragment or ""259 260 @property261 def raw(self) -> RawURL:262+ """263+ The URL in the raw representation used by the low level264+ transport API. For example, see `httpcore`.265+266+ Provides the (scheme, host, port, target) for the outgoing request.267+ """268 return (269 self.scheme.encode("ascii"),270 self.host.encode("ascii"),271 self.port,161- self.full_path.encode("ascii"),272+ self.raw_path,273 )274 275 @property276 def is_ssl(self) -> bool:14 unmodified lines291 return bool(self.scheme and self.host)292 293 @property294 def is_relative_url(self) -> bool:295+ """296+ Return `False` for absolute URLs such as 'http://example.com/path',297+ and `True` for relative URLs such as '/path'.298+ """299 return not self.is_absolute_url300 301 def copy_with(self, **kwargs: typing.Any) -> "URL":187- if (188- "username" in kwargs189- or "password" in kwargs190- or "host" in kwargs191- or "port" in kwargs192- ):193- host = kwargs.pop("host", self.host)194- port = kwargs.pop("port", self.port)302+ """303+ Copy this URL, returning a new URL with some components altered.304+ Accepts the same set of parameters as the components that are made305+ available via properties on the `URL` class.306+307+ For example:308+309+ url = httpx.URL("https://www.example.com").copy_with(username="jo@gmail.com", password="a secret")310+ assert url == "https://jo%40email.com:a%20secret@www.example.com"311+ """312+ allowed = {313+ "scheme": str,314+ "username": str,315+ "password": str,316+ "userinfo": bytes,317+ "host": str,318+ "port": int,319+ "netloc": str,320+ "path": str,321+ "query": bytes,322+ "raw_path": bytes,323+ "fragment": str,324+ }325+ for key, value in kwargs.items():326+ if key not in allowed:327+ message = f"{key!r} is an invalid keyword argument for copy_with()"328+ raise TypeError(message)329+ if value is not None and not isinstance(value, allowed[key]):330+ expected = allowed[key].__name__331+ seen = type(value).__name__332+ message = f"Argument {key!r} must be {expected} but got {seen}"333+ raise TypeError(message)334+335+ # Replace username, password, userinfo, host, port, netloc with "authority" for rfc3986336+ if "username" in kwargs or "password" in kwargs:337+ # Consolidate username and password into userinfo.338 username = quote(kwargs.pop("username", self.username) or "")339 password = quote(kwargs.pop("password", self.password) or "")340+ userinfo = f"{username}:{password}" if password else username341+ kwargs["userinfo"] = userinfo.encode("ascii")342 198- authority = host199- if port is not None:200- authority += f":{port}"201- if username:202- userpass = username203- if password:204- userpass += f":{password}"205- authority = f"{userpass}@{authority}"343+ if "host" in kwargs or "port" in kwargs:344+ # Consolidate host and port into netloc.345+ host = kwargs.pop("host", self.host) or ""346+ port = kwargs.pop("port", self.port)347+ kwargs["netloc"] = f"{host}:{port}" if port is not None else host348 349+ if "userinfo" in kwargs or "netloc" in kwargs:350+ # Consolidate userinfo and netloc into authority.351+ userinfo = (kwargs.pop("userinfo", self.userinfo) or b"").decode("ascii")352+ netloc = kwargs.pop("netloc", self.netloc) or ""353+ authority = f"{userinfo}@{netloc}" if userinfo else netloc354 kwargs["authority"] = authority355 356+ if "raw_path" in kwargs:357+ raw_path = kwargs.pop("raw_path") or b""358+ path, has_query, query = raw_path.decode("ascii").partition("?")359+ kwargs["path"] = path360+ kwargs["query"] = query if has_query else None361+362+ else:363+ # Ensure path=<url quoted str> for rfc3986364+ if kwargs.get("path") is not None:365+ kwargs["path"] = quote(kwargs["path"])366+367+ # Ensure query=<str> for rfc3986368+ if kwargs.get("query") is not None:369+ kwargs["query"] = kwargs["query"].decode("ascii")370+371 return URL(self._uri_reference.copy_with(**kwargs).unsplit())372 373 def join(self, url: URLTypes) -> "URL":374 """375 Return an absolute URL, using this URL as the base.376+377+ Eg.378+379+ url = httpx.URL("https://www.example.com/test")380+ url = url.join("/new/path")381+ assert url == "https://www.example.com/test/new/path"382 """383 if self.is_relative_url:384 return URL(url)385 15 unmodified lines401 def __repr__(self) -> str:402 class_name = self.__class__.__name__403 url_str = str(self)404 if self._uri_reference.userinfo:405+ username = quote(self.username)406 url_str = (407 rfc3986.urlparse(url_str)239- .copy_with(userinfo=f"{self.username}:[secure]")408+ .copy_with(userinfo=f"{username}:[secure]")409 .unsplit()410 )411 return f"{class_name}({url_str!r})"412 408 unmodified lines821 has_content_length = (822 "content-length" in self.headers or "transfer-encoding" in self.headers823 )824 656- if not has_host and self.url.authority:657- host = self.url.copy_with(username=None, password=None).authority658- auto_headers.append((b"host", host.encode("ascii")))825+ if not has_host and self.url.host:826+ default_port = {"http": 80, "https": 443}.get(self.url.scheme)827+ if self.url.port is None or self.url.port == default_port:828+ host_header = self.url.host.encode("ascii")829+ else:830+ host_header = self.url.netloc.encode("ascii")831+ auto_headers.append((b"host", host_header))832 if not has_content_length and self.method in ("POST", "PUT", "PATCH"):833 auto_headers.append((b"content-length", b"0"))834 835 self.headers = Headers(auto_headers + self.headers.raw)646 unmodified linesmodified:tests/models/test_requests.py+4 added-2 removed
170 unmodified lines171 url = "http://example.org"172 request = httpx.Request("GET", url)173 assert request.url.scheme == "http"174 assert request.url.port is None175- assert request.url.full_path == "/"175+ assert request.url.path == "/"176+ assert request.url.raw_path == b"/"177 178 url = "https://example.org/abc?foo=bar"179 request = httpx.Request("GET", url)180 assert request.url.scheme == "https"181 assert request.url.port is None181- assert request.url.full_path == "/abc?foo=bar"182+ assert request.url.path == "/abc"183+ assert request.url.raw_path == b"/abc?foo=bar"modified:tests/models/test_url.py+81 added-6 removed
63 unmodified lines64 url = httpx.URL("https://example.org:123/path/to/somewhere?abc=123#anchor")65 assert url.scheme == "https"66 assert url.host == "example.org"67 assert url.port == 12368- assert url.authority == "example.org:123"68 assert url.path == "/path/to/somewhere"70- assert url.query == "abc=123"69+ assert url.query == b"abc=123"70+ assert url.raw_path == b"/path/to/somewhere?abc=123"71 assert url.fragment == "anchor"72 assert (73 repr(url) == "URL('https://example.org:123/path/to/somewhere?abc=123#anchor')"74 )99 unmodified lines174 175 assert all(url in urls for url in url_set)176 177 178-def test_url_copywith_for_authority():178+def test_url_copywith_authority_subcomponents():179 copy_with_kwargs = {180 "username": "username",181 "password": "password",182 "port": 444,183 "host": "example.net",184 }185 url = httpx.URL("https://example.org")186 new = url.copy_with(**copy_with_kwargs)187- for k, v in copy_with_kwargs.items():188- assert getattr(new, k) == v187 assert str(new) == "https://username:password@example.net:444"188 189 192-def test_url_copywith_for_userinfo():190+def test_url_copywith_netloc():191 copy_with_kwargs = {192+ "netloc": "example.net:444",193+ }194+ url = httpx.URL("https://example.org")195+ new = url.copy_with(**copy_with_kwargs)196+ assert str(new) == "https://example.net:444"197+198+199+def test_url_copywith_userinfo_subcomponents():200+ copy_with_kwargs = {201 "username": "tom@example.org",202 "password": "abc123@ %",203 }204 url = httpx.URL("https://example.org")205 new = url.copy_with(**copy_with_kwargs)206 assert str(new) == "https://tom%40example.org:abc123%40%20%25@example.org"207 assert new.username == "tom@example.org"208 assert new.password == "abc123@ %"209+ assert new.userinfo == b"tom%40example.org:abc123%40%20%25"210 211 212+def test_url_copywith_invalid_component():213+ url = httpx.URL("https://example.org")214+ with pytest.raises(TypeError):215+ url.copy_with(pathh="/incorrect-spelling")216+ with pytest.raises(TypeError):217+ url.copy_with(userinfo="should be bytes")218+219+220+def test_url_copywith_urlencoded_path():221+ url = httpx.URL("https://example.org")222+ url = url.copy_with(path="/path to somewhere")223+ assert url.path == "/path to somewhere"224+ assert url.query == b""225+ assert url.raw_path == b"/path%20to%20somewhere"226+227+228+def test_url_copywith_query():229+ url = httpx.URL("https://example.org")230+ url = url.copy_with(query=b"a=123")231+ assert url.path == "/"232+ assert url.query == b"a=123"233+ assert url.raw_path == b"/?a=123"234+235+236+def test_url_copywith_raw_path():237+ url = httpx.URL("https://example.org")238+ url = url.copy_with(raw_path=b"/some/path")239+ assert url.path == "/some/path"240+ assert url.query == b""241+ assert url.raw_path == b"/some/path"242+243+ url = httpx.URL("https://example.org")244+ url = url.copy_with(raw_path=b"/some/path?")245+ assert url.path == "/some/path"246+ assert url.query == b""247+ assert url.raw_path == b"/some/path?"248+249+ url = httpx.URL("https://example.org")250+ url = url.copy_with(raw_path=b"/some/path?a=123")251+ assert url.path == "/some/path"252+ assert url.query == b"a=123"253+ assert url.raw_path == b"/some/path?a=123"254+255+256 def test_url_invalid():257 with pytest.raises(httpx.InvalidURL):258 httpx.URL("https://😇/")259 3 unmodified lines263 pass264 265 with pytest.raises(TypeError):266 httpx.URL(ExternalURLClass()) # type: ignore267+268+269+def test_url_with_empty_query():270+ """271+ URLs with and without a trailing `?` but an empty query component272+ should preserve the information on the raw path.273+ """274+ url = httpx.URL("https://www.example.com/path")275+ assert url.path == "/path"276+ assert url.query == b""277+ assert url.raw_path == b"/path"278+279+ url = httpx.URL("https://www.example.com/path?")280+ assert url.path == "/path"281+ assert url.query == b""282+ assert url.raw_path == b"/path?"283+284+285+def test_url_with_url_encoded_path():286+ url = httpx.URL("https://www.example.com/path%20to%20somewhere")287+ assert url.path == "/path to somewhere"288+ assert url.query == b""289+ assert url.raw_path == b"/path%20to%20somewhere"modified:setup.cfg+2 added-2 removed
1 [flake8]2 ignore = W503, E203, B3053-max-line-length = 883+max-line-length = 1204 5 [mypy]6 disallow_untyped_defs = True7 ignore_missing_imports = True5 unmodified lines13 [tool:isort]14 profile = black15 combine_as_imports = True16 known_first_party = httpx,tests17-known_third_party = brotli,certifi,chardet,cryptography,httpcore,pytest,rfc3986,setuptools,sniffio,trio,trustme,uvicorn17+known_third_party = brotli,certifi,cryptography,httpcore,pytest,rfc3986,setuptools,sniffio,trio,trustme,uvicorn18 19 [tool:pytest]20 addopts = --cov=httpx --cov=tests -rxXs21 markers =1 unmodified line