Differentiate between 'url.host' and 'url.raw_host' (#1590)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Differentiate between 'url.host' and 'url.raw_host'
authored by Tom Christie · committed by GitHub · parent d98e9e7 · Browse files · 2 files·+114 added−40 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+114 added−40 removed
- tests:+25 added−12 removed
- other:+89 added−28 removed
Provenance
- Commit
39d8ee6- Tree
c5d322f- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
d98e9e7
2 files changed+114 added−40 removed
modified:httpx/_models.py+89 added-28 removed
6 unmodified lines7 from collections.abc import MutableMapping8 from http.cookiejar import Cookie, CookieJar9 from urllib.parse import parse_qsl, quote, unquote, urlencode10 11+import idna12 import rfc398613 import rfc3986.exceptions14 15 from ._content import ByteStream, UnattachedStream, encode_request, encode_response44 unmodified lines60 61 62 class URL:63 """63- url = httpx.URL("HTTPS://jo%40email.com:a%20secret@example.com:1234/pa%20th?search=ab#anchorlink")64+ url = httpx.URL("HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink")65 66 assert url.scheme == "https"67 assert url.username == "jo@email.com"68 assert url.password == "a secret"69 assert url.userinfo == b"jo%40email.com:a%20secret"69- assert url.host == "example.com"70+ assert url.host == "müller.de"71+ assert url.raw_host == b"xn--mller-kva.de"72 assert url.port == 123471- assert url.netloc == "example.com:1234"73+ assert url.netloc == b"xn--mller-kva.de:1234"74 assert url.path == "/pa th"75 assert url.query == b"?search=ab"76 assert url.raw_path == b"/pa%20th?search=ab"77 assert url.fragment == "anchorlink"78 79 The components of a URL are broken down like this:80 79- https://jo%40email.com:a%20secret@example.com:1234/pa%20th?search=ab#anchorlink80- [scheme][ username ] [password] [ host ][port][ path ] [ query ] [fragment]81- [ userinfo ] [ netloc ][ raw_path ]81+ https://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink82+ [scheme] [ username ] [password] [ host ][port][ path ] [ query ] [fragment]83+ [ userinfo ] [ netloc ][ raw_path ]84 85 Note that:86 87 * `url.scheme` is normalized to always be lowercased.88 87- * `url.host` is normalized to always be lowercased, and is IDNA encoded. For instance:88- url = httpx.URL("http://中国.icom.museum")89- assert url.host == "xn--fiqs8s.icom.museum"89+ * `url.host` is normalized to always be lowercased. Internationalized domain90+ names are represented in unicode, without IDNA encoding applied. For instance:91 92+ url = httpx.URL("http://中国.icom.museum")93+ assert url.host == "中国.icom.museum"94+ url = httpx.URL("http://xn--fiqs8s.icom.museum")95+ assert url.host == "中国.icom.museum"96+97+ * `url.raw_host` is normalized to always be lowercased, and is IDNA encoded.98+99+ url = httpx.URL("http://中国.icom.museum")100+ assert url.raw_host == b"xn--fiqs8s.icom.museum"101+ url = httpx.URL("http://xn--fiqs8s.icom.museum")102+ assert url.raw_host == b"xn--fiqs8s.icom.museum"103+104 * `url.userinfo` is raw bytes, without URL escaping. Usually you'll want to work with105 `url.username` and `url.password` instead, which handle the URL escaping.106 107 * `url.raw_path` is raw bytes of both the path and query, without URL escaping.55 unmodified lines163 """164 return self._uri_reference.scheme or ""165 166 @property167+ def raw_scheme(self) -> bytes:168+ """169+ The raw bytes representation of the URL scheme, such as b"http", b"https".170+ Always normalised to lowercase.171+ """172+ return self.scheme.encode("ascii")173+174+ @property175 def userinfo(self) -> bytes:176 """177 The URL userinfo as a raw bytestring.178 For example: b"jo%40email.com:a%20secret".22 unmodified lines201 @property202 def host(self) -> str:203 """204 The URL host as a string.184- Always normlized to lowercase, and IDNA encoded.205+ Always normalized to lowercase, with IDNA hosts decoded into unicode.206 207 Examples:208 209 url = httpx.URL("http://www.EXAMPLE.org")210 assert url.host == "www.example.org"211 212 url = httpx.URL("http://中国.icom.museum")192- assert url.host == "xn--fiqs8s.icom.museum"213+ assert url.host == "中国.icom.museum"214 215+ url = httpx.URL("http://xn--fiqs8s.icom.museum")216+ assert url.host == "中国.icom.museum"217+218 url = httpx.URL("https://[::ffff:192.168.0.1]")219 assert url.host == "::ffff:192.168.0.1"220 """197- host: str = self._uri_reference.host221+ host: str = self._uri_reference.host or ""222 223 if host and ":" in host and host[0] == "[":224 # it's an IPv6 address225 host = host.lstrip("[").rstrip("]")226 203- return host or ""227+ if host.startswith("xn--"):228+ host = idna.decode(host)229 230+ return host231+232 @property233+ def raw_host(self) -> bytes:234+ """235+ The raw bytes representation of the URL host.236+ Always normalized to lowercase, and IDNA encoded.237+238+ Examples:239+240+ url = httpx.URL("http://www.EXAMPLE.org")241+ assert url.raw_host == b"www.example.org"242+243+ url = httpx.URL("http://中国.icom.museum")244+ assert url.raw_host == b"xn--fiqs8s.icom.museum"245+246+ url = httpx.URL("http://xn--fiqs8s.icom.museum")247+ assert url.raw_host == b"xn--fiqs8s.icom.museum"248+249+ url = httpx.URL("https://[::ffff:192.168.0.1]")250+ assert url.raw_host == b"::ffff:192.168.0.1"251+ """252+ host: str = self._uri_reference.host or ""253+254+ if host and ":" in host and host[0] == "[":255+ # it's an IPv6 address256+ host = host.lstrip("[").rstrip("]")257+258+ return host.encode("ascii")259+260+ @property261 def port(self) -> typing.Optional[int]:262 """263 The URL port as an integer.264 """265 port = self._uri_reference.port266 return int(port) if port else None267 268 @property214- def netloc(self) -> str:269+ def netloc(self) -> bytes:270 """216- Either `<host>` or `<host>:<port>` as a string.217- Always normlized to lowercase, and IDNA encoded.271+ Either `<host>` or `<host>:<port>` as bytes.272+ Always normalized to lowercase, and IDNA encoded.273 """274 host = self._uri_reference.host or ""275 port = self._uri_reference.port221- return host if port is None else f"{host}:{port}"276+ netloc = host.encode("ascii")277+ if port:278+ netloc = netloc + b":" + str(port).encode("ascii")279+ return netloc280 281 @property282 def path(self) -> str:283 """50 unmodified lines334 335 Provides the (scheme, host, port, target) for the outgoing request.336 """337 return (280- self.scheme.encode("ascii"),281- self.host.encode("ascii"),338+ self.raw_scheme,339+ self.raw_host,340 self.port,341 self.raw_path,342 )343 6 unmodified lines350 # We don't use `.is_absolute` from `rfc3986` because it treats351 # URLs with a fragment portion as not absolute.352 # What we actually care about is if the URL provides353 # a scheme and hostname to which connections should be made.296- return bool(self.scheme and self.host)354+ return bool(self._uri_reference.scheme and self._uri_reference.host)355 356 @property357 def is_relative_url(self) -> bool:358 """19 unmodified lines378 "password": str,379 "userinfo": bytes,380 "host": str,381 "port": int,324- "netloc": str,382+ "netloc": bytes,383 "path": str,384 "query": bytes,385 "raw_path": bytes,386 "fragment": str,24 unmodified lines411 if host and ":" in host and host[0] != "[":412 # it's an IPv6 address, so it should be hidden under bracket413 host = f"[{host}]"414 357- kwargs["netloc"] = f"{host}:{port}" if port is not None else host415+ kwargs["netloc"] = (416+ f"{host}:{port}".encode("ascii")417+ if port is not None418+ else host.encode("ascii")419+ )420 421 if "userinfo" in kwargs or "netloc" in kwargs:422 # Consolidate userinfo and netloc into authority.423 userinfo = (kwargs.pop("userinfo", self.userinfo) or b"").decode("ascii")362- netloc = kwargs.pop("netloc", self.netloc) or ""424+ netloc = (kwargs.pop("netloc", self.netloc) or b"").decode("ascii")425 authority = f"{userinfo}@{netloc}" if userinfo else netloc426 kwargs["authority"] = authority427 428 if "raw_path" in kwargs:480 unmodified lines909 "Content-Length" in self.headers or "Transfer-Encoding" in self.headers910 )911 912 if not has_host and self.url.host:851- default_port = {"http": 80, "https": 443}.get(self.url.scheme)852- if self.url.port is None or self.url.port == default_port:853- host_header = self.url.host.encode("ascii")854- else:855- host_header = self.url.netloc.encode("ascii")913+ default_port = {"http": b":80", "https": b":443"}.get(self.url.scheme, b"")914+ host_header = self.url.netloc915+ if host_header.endswith(default_port):916+ host_header = host_header[: -len(default_port)]917 auto_headers.append((b"Host", host_header))918 if not has_content_length and self.method in ("POST", "PUT", "PATCH"):919 auto_headers.append((b"Content-Length", b"0"))920 710 unmodified linesmodified:tests/models/test_url.py+25 added-12 removed
2 unmodified lines3 import httpx4 5 6 @pytest.mark.parametrize(7- "given,idna,host,scheme,port",7+ "given,idna,host,raw_host,scheme,port",8 [9 (10 "http://中国.icom.museum:80/",11 "http://xn--fiqs8s.icom.museum:80/",12- "xn--fiqs8s.icom.museum",12+ "中国.icom.museum",13+ b"xn--fiqs8s.icom.museum",14 "http",15 80,16 ),17 (18 "http://Königsgäßchen.de",19 "http://xn--knigsgchen-b4a3dun.de",20+ "königsgäßchen.de",19- "xn--knigsgchen-b4a3dun.de",21+ b"xn--knigsgchen-b4a3dun.de",22 "http",23 None,24 ),23- ("https://faß.de", "https://xn--fa-hia.de", "xn--fa-hia.de", "https", None),25 (26+ "https://faß.de",27+ "https://xn--fa-hia.de",28+ "faß.de",29+ b"xn--fa-hia.de",30+ "https",31+ None,32+ ),33+ (34 "https://βόλος.com:443",35 "https://xn--nxasmm1c.com:443",36+ "βόλος.com",27- "xn--nxasmm1c.com",37+ b"xn--nxasmm1c.com",38 "https",39 443,40 ),41 (42 "http://ශ්රී.com:444",43 "http://xn--10cl1a0b660p.com:444",44+ "ශ්රී.com",34- "xn--10cl1a0b660p.com",45+ b"xn--10cl1a0b660p.com",46 "http",47 444,48 ),49 (50 "https://نامهای.com:4433",51 "https://xn--mgba3gch31f060k.com:4433",52+ "نامهای.com",41- "xn--mgba3gch31f060k.com",53+ b"xn--mgba3gch31f060k.com",54 "https",55 4433,56 ),57 ],5 unmodified lines63 "http_with_custom_port",64 "https_with_custom_port",65 ],66 )55-def test_idna_url(given, idna, host, scheme, port):67+def test_idna_url(given, idna, host, raw_host, scheme, port):68 url = httpx.URL(given)69 assert url == httpx.URL(idna)70 assert url.host == host71+ assert url.raw_host == raw_host72 assert url.scheme == scheme73 assert url.port == port74 75 133 unmodified lines209 210 211 def test_url_copywith_netloc():212 copy_with_kwargs = {200- "netloc": "example.net:444",213+ "netloc": b"example.net:444",214 }215 url = httpx.URL("https://example.org")216 new = url.copy_with(**copy_with_kwargs)217 assert str(new) == "https://example.net:444"95 unmodified lines313 def test_ipv6_url():314 url = httpx.URL("http://[::ffff:192.168.0.1]:5678/")315 316 assert url.host == "::ffff:192.168.0.1"304- assert url.netloc == "[::ffff:192.168.0.1]:5678"317+ assert url.netloc == b"[::ffff:192.168.0.1]:5678"318 319 320 @pytest.mark.parametrize(321 "url_str",7 unmodified lines329 def test_ipv6_url_copy_with_host(url_str, new_host):330 url = httpx.URL(url_str).copy_with(host=new_host)331 332 assert url.host == "::ffff:192.168.0.1"320- assert url.netloc == "[::ffff:192.168.0.1]:1234"333+ assert url.netloc == b"[::ffff:192.168.0.1]:1234"334 assert str(url) == "http://[::ffff:192.168.0.1]:1234"335 336 337 @pytest.mark.parametrize("host", [b"[::ffff:192.168.0.1]", b"::ffff:192.168.0.1"])1 unmodified line339 raw_url = (b"https", host, 443, b"/")340 url = httpx.URL(raw_url)341 342 assert url.host == "::ffff:192.168.0.1"330- assert url.netloc == "[::ffff:192.168.0.1]:443"343+ assert url.netloc == b"[::ffff:192.168.0.1]:443"344 assert str(url) == "https://[::ffff:192.168.0.1]:443/"