Add idna support. More tests.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by Tom Christie · parent 302fe93 · Browse files · 8 files·+71 added−20 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+71 added−20 removed
- tests:+13 added−1 removed
- other:+58 added−19 removed
Provenance
- Commit
b948798- Tree
104e922- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
302fe93
8 files changed+71 added−20 removed
modified:httpcore/adapters/redirects.py+3 added-4 removed
96 unmodified lines97 location = response.headers["Location"]98 99 url = URL(location, allow_relative=True)100 101- # Facilitate relative 'location' headers, as allowed by RFC 7231.101+ # Facilitate relative 'Location' headers, as allowed by RFC 7231.102 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')103- # Compliant with RFC3986, we percent encode the url.104- if not url.is_absolute:105- url = url.resolve_with(request.url.copy_with(fragment=None))103+ if url.is_relative_url:104+ url = url.resolve_with(request.url)105 106 # Attach previous fragment if needed (RFC 7231 7.1.2)107 if request.url.fragment and not url.fragment:108 url = url.copy_with(fragment=request.url.fragment)22 unmodified linesmodified:httpcore/models.py+37 added-9 removed
1 import cgi2 import typing3 4 import chardet5+import idna6 import rfc39867 8 from .config import SSLConfig, TimeoutConfig9 from .decoders import (24 unmodified lines34 35 36 class URL:37 def __init__(self, url: URLTypes, allow_relative: bool = False) -> None:37- if isinstance(url, str):38- self.components = rfc3986.api.uri_reference(url).normalize()39- elif isinstance(url, rfc3986.uri.URIReference):38+ if isinstance(url, rfc3986.uri.URIReference):39 self.components = url40+ elif isinstance(url, str):41+ self.components = rfc3986.api.uri_reference(url)42 else:43 self.components = url.components44 45+ # Handle IDNA domain names.46+ if self.components.authority:47+ idna_authority = self.components.authority.encode("idna").decode("ascii")48+ if idna_authority != self.components.authority:49+ self.components = self.components.copy_with(authority=idna_authority)50+51+ # Normalize schema and domain name.52+ self.components = self.components.normalize()53+54+ # Enforce absolute URLs by default.55 if not allow_relative:56 if not self.scheme:57 raise InvalidURL("No scheme included in URL.")58 if self.scheme not in ("http", "https"):59 raise InvalidURL('URL scheme must be "http" or "https".')60 if not self.host:50- raise InvalidURL("No hostname included in URL.")61+ raise InvalidURL("No host included in URL.")62 63 @property64 def scheme(self) -> str:65 return self.components.scheme or ""37 unmodified lines103 def is_secure(self) -> bool:104 return self.components.scheme == "https"105 106 @property96- def is_absolute(self) -> bool:97- return self.components.is_absolute()107+ def is_absolute_url(self) -> bool:108+ """109+ Return `True` for absolute URLs such as 'http://example.com/path',110+ and `False` for relative URLs such as '/path'.111+ """112+ # We don't use rfc3986's `is_absolute` because it treats113+ # URLs with a fragment portion as not absolute.114+ # What we actually care about is if the URL provides115+ # a scheme and hostname to which connections should be made.116+ return self.components.scheme and self.components.host117 118 @property119+ def is_relative_url(self) -> bool:120+ return not self.is_absolute_url121+122+ @property123 def origin(self) -> "Origin":124 return Origin(self)125 126 def copy_with(self, **kwargs: typing.Any) -> "URL":127 return URL(self.components.copy_with(**kwargs))128 129 def resolve_with(self, base_url: URLTypes) -> "URL":107- if isinstance(base_url, URL):108- base_url = base_url.components109- return URL(self.components.resolve_with(base_url))130+ """131+ Return an absolute URL, using base_url as the base.132+ """133+ # We drop any fragment portion, because RFC 3986 strictly134+ # treats URLs with a fragment portion as not being absolute URLs,135+ # but we want to treat them as such for the purposes of136+ base_url = URL(base_url).copy_with(fragment=None)137+ return URL(self.components.resolve_with(base_url.components))138 139 def __hash__(self) -> int:140 return hash(str(self))141 467 unmodified linesmodified:httpcore/sync.py+4 added
27 unmodified lines28 @property29 def content(self) -> bytes:30 return self._response.content31 32+ @property33+ def text(self) -> str:34+ return self._response.text35+36 def read(self) -> bytes:37 return self._loop.run_until_complete(self._response.read())38 39 def stream(self) -> typing.Iterator[bytes]:48 unmodified linesmodified:tests/dispatch/test_http2.py+4 added-1 removed
68 unmodified lines69 "body": request_data.decode(),70 }71 ).encode()72 73- response_headers = ((b":status", b"200"),)73+ response_headers = (74+ (b":status", b"200"),75+ (b"content-length", str(len(response_body)).encode()),76+ )77 self.conn.send_headers(stream_id, response_headers)78 self.conn.send_data(stream_id, response_body, end_stream=True)79 self.buffer += self.conn.data_to_send()80 39 unmodified linesadded:tests/models/test_url.py+7 added
1+from httpcore import URL2+3+4+def test_idna_url():5+ url = URL("http://中国.icom.museum:80/")6+ assert url == URL("http://xn--fiqs8s.icom.museum:80/")7+ assert url.host == "xn--fiqs8s.icom.museum"modified:tests/test_sync.py+2 added
27 unmodified lines28 with httpcore.SyncConnectionPool() as http:29 response = http.request("GET", "http://127.0.0.1:8000/")30 assert response.status_code == 20031 assert response.content == b"Hello, world!"32+ assert response.text == "Hello, world!"33 34 35 @threadpool36 def test_post(server):37 with httpcore.SyncConnectionPool() as http:38 response = http.request("POST", "http://127.0.0.1:8000/", body=b"Hello, world!")39 assert response.status_code == 20040+ assert response.reason_phrase == "OK"41 42 43 @threadpool44 def test_stream_response(server):16 unmodified linesmodified:requirements.txt+6 added-5 removed
1 certifi2-chardet3-h114-h25-rfc39862+chardet==3.*3+h11==0.8.*4+h2==3.*5+idna==2.*6+rfc3986==1.*7 8 # Optional8-brotlipy9+brotlipy==0.7.*10 11 12 # Testing13 autoflake7 unmodified linesmodified:setup.py+8 added-1 removed
45 unmodified lines46 author="Tom Christie",47 author_email="tom@tomchristie.com",48 packages=get_packages("httpcore"),49 data_files=[("", ["LICENSE.md"])],50- install_requires=["h11", "h2", "certifi", "chardet", "rfc3986"],50+ install_requires=[51+ "certifi",52+ "chardet==3.*",53+ "h11==0.8.*",54+ "h2==3.*",55+ "idna==2.*",56+ "rfc3986==1.*"57+ ],58 classifiers=[59 "Development Status :: 3 - Alpha",60 "Environment :: Web Environment",61 "Intended Audience :: Developers",9 unmodified lines