Skip to content
Myr

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

8 files+71 added−20 removed

modified:httpcore/adapters/redirects.py+3 added-4 removed
96 unmodified lines
97 location = response.headers["Location"]9899 url = URL(location, allow_relative=True)100101 # 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)105106 # 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 lines
modified:httpcore/models.py+37 added-9 removed
1import cgi2import typing34import chardet5import idna6import rfc398678from .config import SSLConfig, TimeoutConfig9from .decoders import (
24 unmodified lines
343536class 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.components4445 # 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)5051 # Normalize schema and domain name.52 self.components = self.components.normalize()5354 # 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.")6263 @property64 def scheme(self) -> str:65 return self.components.scheme or ""
37 unmodified lines
103 def is_secure(self) -> bool:104 return self.components.scheme == "https"105106 @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.host117118 @property119 def is_relative_url(self) -> bool:120 return not self.is_absolute_url121122 @property123 def origin(self) -> "Origin":124 return Origin(self)125126 def copy_with(self, **kwargs: typing.Any) -> "URL":127 return URL(self.components.copy_with(**kwargs))128129 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))138139 def __hash__(self) -> int:140 return hash(str(self))141
467 unmodified lines
modified:httpcore/sync.py+4 added
27 unmodified lines
28 @property29 def content(self) -> bytes:30 return self._response.content3132 @property33 def text(self) -> str:34 return self._response.text3536 def read(self) -> bytes:37 return self._loop.run_until_complete(self._response.read())3839 def stream(self) -> typing.Iterator[bytes]:
48 unmodified lines
modified:tests/dispatch/test_http2.py+4 added-1 removed
68 unmodified lines
69 "body": request_data.decode(),70 }71 ).encode()7273 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 lines
added:tests/models/test_url.py+7 added
1from httpcore import URL234def 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 lines
28 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!"333435@threadpool36def 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"414243@threadpool44def test_stream_response(server):
16 unmodified lines
modified:requirements.txt+6 added-5 removed
1certifi2chardet3h114h25rfc39862chardet==3.*3h11==0.8.*4h2==3.*5idna==2.*6rfc3986==1.*78# Optional8brotlipy9brotlipy==0.7.*101112# Testing13autoflake
7 unmodified lines
modified:setup.py+8 added-1 removed
45 unmodified lines
46 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