Skip to content
Myr

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

5 files+302 added−52 removed

modified:httpx/_auth.py+1 added-1 removed
215 unmodified lines
216 return hash_func(data).hexdigest().encode()217218 A1 = b":".join((self._username, challenge.realm, self._password))219220 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 lines
modified:httpx/_models.py+214 added-41 removed
60 unmodified lines
61)626364class URL:65 """66 url = httpx.URL("HTTPS://jo%40email.com:a%20secret@example.com:1234/pa%20th?search=ab#anchorlink")6768 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"7980 The components of a URL are broken down like this:8182 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 ]8586 Note that:8788 * `url.scheme` is normalized to always be lowercased.8990 * `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"9394 * `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.9697 * `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.100101 * `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 """104105 def __init__(106 self, url: typing.Union["URL", str, RawURL] = "", params: QueryParamTypes = None107 ) -> None:108 if isinstance(url, (str, tuple)):
32 unmodified lines
141 self._uri_reference = self._uri_reference.copy_with(query=query_string)142143 @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 ""150151 @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")159160 @property116 def userinfo(self) -> str:117 return self._uri_reference.userinfo or ""118119 @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])168169 @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])177178 @property179 def host(self) -> str:180 """181 The URL host as a string.182 Always normlized to lowercase, and IDNA encoded.183184 Examples:185186 url = httpx.URL("http://www.EXAMPLE.org")187 assert url.host == "www.example.org"188189 url = httpx.URL("http://中国.icom.museum")190 assert url.host == "xn--fiqs8s.icom.museum"191 """192 return self._uri_reference.host or ""193194 @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 None201202 @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}"211212 @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.216217 For example:218219 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)224225 @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")234235 @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.240241 For example:242243 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")251252 @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 ""259260 @property261 def raw(self) -> RawURL:262 """263 The URL in the raw representation used by the low level264 transport API. For example, see `httpcore`.265266 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 )274275 @property276 def is_ssl(self) -> bool:
14 unmodified lines
291 return bool(self.scheme and self.host)292293 @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_url300301 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.306307 For example:308309 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)334335 # 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")342198 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 host348349 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"] = authority355356 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 None361362 else:363 # Ensure path=<url quoted str> for rfc3986364 if kwargs.get("path") is not None:365 kwargs["path"] = quote(kwargs["path"])366367 # Ensure query=<str> for rfc3986368 if kwargs.get("query") is not None:369 kwargs["query"] = kwargs["query"].decode("ascii")370371 return URL(self._uri_reference.copy_with(**kwargs).unsplit())372373 def join(self, url: URLTypes) -> "URL":374 """375 Return an absolute URL, using this URL as the base.376377 Eg.378379 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 lines
401 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 lines
821 has_content_length = (822 "content-length" in self.headers or "transfer-encoding" in self.headers823 )824656 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"))834835 self.headers = Headers(auto_headers + self.headers.raw)
646 unmodified lines
modified:tests/models/test_requests.py+4 added-2 removed
170 unmodified lines
171 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"/"177178 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 lines
64 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 lines
174175 assert all(url in urls for url in url_set)176177178def test_url_copywith_for_authority():178def 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"188189192def test_url_copywith_for_userinfo():190def 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"197198199def 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"210211212def 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")218219220def 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"226227228def 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"234235236def 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"242243 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?"248249 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"254255256def test_url_invalid():257 with pytest.raises(httpx.InvalidURL):258 httpx.URL("https://😇/")259
3 unmodified lines
263 pass264265 with pytest.raises(TypeError):266 httpx.URL(ExternalURLClass()) # type: ignore267268269def 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"278279 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?"283284285def 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]2ignore = W503, E203, B3053max-line-length = 883max-line-length = 12045[mypy]6disallow_untyped_defs = True7ignore_missing_imports = True
5 unmodified lines
13[tool:isort]14profile = black15combine_as_imports = True16known_first_party = httpx,tests17known_third_party = brotli,certifi,chardet,cryptography,httpcore,pytest,rfc3986,setuptools,sniffio,trio,trustme,uvicorn17known_third_party = brotli,certifi,cryptography,httpcore,pytest,rfc3986,setuptools,sniffio,trio,trustme,uvicorn1819[tool:pytest]20addopts = --cov=httpx --cov=tests -rxXs21markers =
1 unmodified line