Finessing interface
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 d652479 · Browse files · 9 files·+215 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
9 files+215 added−52 removed
- tests:+24 added−6 removed
- other:+191 added−46 removed
Provenance
- Commit
d7619a9- Tree
0393613- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
d652479
9 files changed+215 added−52 removed
modified:httpcore/dispatch/http11.py+2 added-2 removed
73 unmodified lines74 if isinstance(event, h11.InformationalResponse):75 event = await self._receive_event(timeout)76 77 assert isinstance(event, h11.Response)78- reason = event.reason.decode("latin1")78+ reason_phrase = event.reason.decode("latin1")79 status_code = event.status_code80 headers = event.headers81 body = self._body_iter(timeout)82 83 response = Response(84 status_code=status_code,85- reason=reason,85+ reason_phrase=reason_phrase,86 protocol="HTTP/1.1",87 headers=headers,88 body=body,89 on_close=self.response_closed,59 unmodified linesmodified:httpcore/client.py+139 added-19 removed
13 unmodified lines14 SSLConfig,15 TimeoutConfig,16 )17 from .dispatch.connection_pool import ConnectionPool18-from .models import URL, Request, Response18+from .models import URL, BodyTypes, HeaderTypes, Request, Response, URLTypes19 20 21 class Client:22 def __init__(13 unmodified lines36 37 async def request(38 self,39 method: str,40- url: typing.Union[str, URL],40+ url: URLTypes,41 *,42- body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",43- headers: typing.List[typing.Tuple[bytes, bytes]] = [],42+ body: BodyTypes = b"",43+ headers: HeaderTypes = None,44 stream: bool = False,45 allow_redirects: bool = True,46- ssl: typing.Optional[SSLConfig] = None,47- timeout: typing.Optional[TimeoutConfig] = None,46+ ssl: SSLConfig = None,47+ timeout: TimeoutConfig = None,48 ) -> Response:49 request = Request(method, url, headers=headers, body=body)50 self.prepare_request(request)51 response = await self.send(6 unmodified lines58 return response59 60 async def get(61 self,62- url: typing.Union[str, URL],62+ url: URLTypes,63 *,64- headers: typing.List[typing.Tuple[bytes, bytes]] = [],64+ headers: HeaderTypes = None,65 stream: bool = False,66- ssl: typing.Optional[SSLConfig] = None,67- timeout: typing.Optional[TimeoutConfig] = None,66+ allow_redirects: bool = True,67+ ssl: SSLConfig = None,68+ timeout: TimeoutConfig = None,69 ) -> Response:70 return await self.request(70- "GET", url, headers=headers, stream=stream, ssl=ssl, timeout=timeout71+ "GET",72+ url,73+ headers=headers,74+ stream=stream,75+ allow_redirects=allow_redirects,76+ ssl=ssl,77+ timeout=timeout,78 )79 80+ async def options(81+ self,82+ url: URLTypes,83+ *,84+ headers: HeaderTypes = None,85+ stream: bool = False,86+ allow_redirects: bool = True,87+ ssl: SSLConfig = None,88+ timeout: TimeoutConfig = None,89+ ) -> Response:90+ return await self.request(91+ "OPTIONS",92+ url,93+ headers=headers,94+ stream=stream,95+ allow_redirects=allow_redirects,96+ ssl=ssl,97+ timeout=timeout,98+ )99+100+ async def head(101+ self,102+ url: URLTypes,103+ *,104+ headers: HeaderTypes = None,105+ stream: bool = False,106+ allow_redirects: bool = False, # Note: Differs to usual default.107+ ssl: SSLConfig = None,108+ timeout: TimeoutConfig = None,109+ ) -> Response:110+ return await self.request(111+ "HEAD",112+ url,113+ headers=headers,114+ stream=stream,115+ allow_redirects=allow_redirects,116+ ssl=ssl,117+ timeout=timeout,118+ )119+120 async def post(121 self,75- url: typing.Union[str, URL],122+ url: URLTypes,123 *,77- body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",78- headers: typing.List[typing.Tuple[bytes, bytes]] = [],124+ body: BodyTypes = b"",125+ headers: HeaderTypes = None,126 stream: bool = False,80- ssl: typing.Optional[SSLConfig] = None,81- timeout: typing.Optional[TimeoutConfig] = None,127+ allow_redirects: bool = True,128+ ssl: SSLConfig = None,129+ timeout: TimeoutConfig = None,130 ) -> Response:131 return await self.request(132 "POST",133 url,134 body=body,135 headers=headers,136 stream=stream,137+ allow_redirects=allow_redirects,138 ssl=ssl,139 timeout=timeout,140 )141 142+ async def put(143+ self,144+ url: URLTypes,145+ *,146+ body: BodyTypes = b"",147+ headers: HeaderTypes = None,148+ stream: bool = False,149+ allow_redirects: bool = True,150+ ssl: SSLConfig = None,151+ timeout: TimeoutConfig = None,152+ ) -> Response:153+ return await self.request(154+ "PUT",155+ url,156+ body=body,157+ headers=headers,158+ stream=stream,159+ allow_redirects=allow_redirects,160+ ssl=ssl,161+ timeout=timeout,162+ )163+164+ async def patch(165+ self,166+ url: URLTypes,167+ *,168+ body: BodyTypes = b"",169+ headers: HeaderTypes = None,170+ stream: bool = False,171+ allow_redirects: bool = True,172+ ssl: SSLConfig = None,173+ timeout: TimeoutConfig = None,174+ ) -> Response:175+ return await self.request(176+ "PATCH",177+ url,178+ body=body,179+ headers=headers,180+ stream=stream,181+ allow_redirects=allow_redirects,182+ ssl=ssl,183+ timeout=timeout,184+ )185+186+ async def delete(187+ self,188+ url: URLTypes,189+ *,190+ body: BodyTypes = b"",191+ headers: HeaderTypes = None,192+ stream: bool = False,193+ allow_redirects: bool = True,194+ ssl: SSLConfig = None,195+ timeout: TimeoutConfig = None,196+ ) -> Response:197+ return await self.request(198+ "DELETE",199+ url,200+ body=body,201+ headers=headers,202+ stream=stream,203+ allow_redirects=allow_redirects,204+ ssl=ssl,205+ timeout=timeout,206+ )207+208 def prepare_request(self, request: Request) -> None:209 self.adapter.prepare_request(request)210 211 async def send(1 unmodified line213 request: Request,214 *,215 stream: bool = False,216 allow_redirects: bool = True,102- ssl: typing.Optional[SSLConfig] = None,103- timeout: typing.Optional[TimeoutConfig] = None,217+ ssl: SSLConfig = None,218+ timeout: TimeoutConfig = None,219 ) -> Response:105- options = {"stream": stream} # type: typing.Dict[str, typing.Any]220+ options = {221+ "stream": stream,222+ "allow_redirects": allow_redirects,223+ } # type: typing.Dict[str, typing.Any]224+225 if ssl is not None:226 options["ssl"] = ssl227 if timeout is not None:228 options["timeout"] = timeout229+230 return await self.adapter.send(request, **options)231 232 async def close(self) -> None:233 await self.adapter.close()11 unmodified linesmodified:httpcore/config.py+2 added
69 unmodified lines70 )71 72 context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)73 74+ context.verify_mode = ssl.CERT_REQUIRED75+76 context.options |= ssl.OP_NO_SSLv277 context.options |= ssl.OP_NO_SSLv378 context.options |= ssl.OP_NO_COMPRESSION79 101 unmodified linesmodified:httpcore/models.py+35 added-23 removed
1-import http1 import typing2 from urllib.parse import urlsplit3 4 from .config import SSLConfig, TimeoutConfig4 unmodified lines9 IdentityDecoder,10 MultiDecoder,11 )12 from .exceptions import ResponseClosed, StreamConsumed13+from .status_codes import codes14-from .utils import normalize_header_key, normalize_header_value14+from .utils import get_reason_phrase, normalize_header_key, normalize_header_value15 16+URLTypes = typing.Union["URL", str]17 18+HeaderTypes = typing.Union[19+ "Headers",20+ typing.Dict[typing.AnyStr, typing.AnyStr],21+ typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],22+]23+24+BodyTypes = typing.Union[bytes, typing.AsyncIterator[bytes]]25+26+27 class URL:18- def __init__(self, url: str = "") -> None:19- self.components = urlsplit(url)28+ def __init__(self, url: URLTypes) -> None:29+ if isinstance(url, str):30+ self.components = urlsplit(url)31+ else:32+ self.components = url.components33+34 if not self.components.scheme:35 raise ValueError("No scheme included in URL.")36 if self.components.scheme not in ("http", "https"):37 raise ValueError('URL scheme must be "http" or "https".')81 unmodified lines119 def __hash__(self) -> int:120 return hash((self.is_ssl, self.hostname, self.port))121 122 109-HeaderTypes = typing.Union[110- "Headers",111- typing.Dict[typing.AnyStr, typing.AnyStr],112- typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],113-]114-115-123 class Headers(typing.MutableMapping[str, str]):124 """125 A case-insensitive multidict.126 """118 unmodified lines245 method: str,246 url: typing.Union[str, URL],247 *,248 headers: HeaderTypes = None,242- body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",249+ body: BodyTypes = b"",250 ):251 self.method = method.upper()252 self.url = URL(url) if isinstance(url, str) else url253 if isinstance(body, bytes):50 unmodified lines304 def __init__(305 self,306 status_code: int,307 *,301- reason: typing.Optional[str] = None,302- protocol: typing.Optional[str] = None,303- headers: typing.List[typing.Tuple[bytes, bytes]] = [],304- body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",308+ reason_phrase: str = None,309+ protocol: str = None,310+ headers: HeaderTypes = None,311+ body: BodyTypes = b"",312 on_close: typing.Callable = None,313 request: Request = None,314 history: typing.List["Response"] = None,315 ):316 self.status_code = status_code310- if not reason:311- try:312- self.reason = http.HTTPStatus(status_code).phrase313- except ValueError as exc:314- self.reason = ""317+ if reason_phrase is None:318+ self.reason_phrase = get_reason_phrase(status_code)319 else:316- self.reason = reason320+ self.reason_phrase = reason_phrase321 self.protocol = protocol322 self.headers = Headers(headers)323 self.on_close = on_close324 self.is_closed = False75 unmodified lines400 401 @property402 def is_redirect(self) -> bool:403 return (400- self.status_code in (301, 302, 303, 307, 308) and "location" in self.headers404+ self.status_code405+ in (406+ codes.moved_permanently,407+ codes.found,408+ codes.see_other,409+ codes.temporary_redirect,410+ codes.permanent_redirect,411+ )412+ and "location" in self.headers413 )modified:httpcore/sync.py+2 added-2 removed
16 unmodified lines17 def status_code(self) -> int:18 return self._response.status_code19 20 @property21- def reason(self) -> str:22- return self._response.reason21+ def reason_phrase(self) -> str:22+ return self._response.reason_phrase23 24 @property25 def headers(self) -> Headers:26 return self._response.headers57 unmodified linesmodified:httpcore/utils.py+11 added
1+import http2 import typing3 from urllib.parse import quote4 5 from .exceptions import InvalidURL63 unmodified lines69 """70 if isinstance(value, bytes):71 return value72 return value.encode("latin-1")73+74+75+def get_reason_phrase(status_code: int) -> str:76+ """77+ Return an HTTP reason phrase, eg. "OK" for 200, or "Not Found" for 404.78+ """79+ try:80+ return http.HTTPStatus(status_code).phrase81+ except ValueError as exc:82+ return ""modified:tests/test_api.py+4 added-4 removed
3 unmodified lines4 5 6 @pytest.mark.asyncio7 async def test_get(server):8+ url = "http://127.0.0.1:8000/"9 async with httpcore.Client() as client:9- response = await client.request("GET", "http://127.0.0.1:8000/")10+ response = await client.get(url)11 assert response.status_code == 20012 assert response.body == b"Hello, world!"13 14 15 @pytest.mark.asyncio16 async def test_post(server):17+ url = "http://127.0.0.1:8000/"18 async with httpcore.Client() as client:17- response = await client.request(18- "POST", "http://127.0.0.1:8000/", body=b"Hello, world!"19- )19+ response = await client.post(url, body=b"Hello, world!")20 assert response.status_code == 20021 22 23 @pytest.mark.asyncio20 unmodified linesmodified:tests/test_config.py+18 added
1+import ssl2+3+import pytest4+5 import httpcore6 7 8+@pytest.mark.asyncio9+async def test_load_ssl_config():10+ ssl_config = httpcore.SSLConfig()11+ context = await ssl_config.load_ssl_context()12+ assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED13+14+15+@pytest.mark.asyncio16+async def test_load_ssl_config_no_verify(verify=False):17+ ssl_config = httpcore.SSLConfig(verify=False)18+ context = await ssl_config.load_ssl_context()19+ assert context.verify_mode == ssl.VerifyMode.CERT_NONE20+21+22 def test_ssl_repr():23 ssl = httpcore.SSLConfig(verify=False)24 assert repr(ssl) == "SSLConfig(cert=None, verify=False)"25 32 unmodified linesmodified:tests/test_responses.py+2 added-2 removed
9 unmodified lines10 11 def test_response():12 response = httpcore.Response(200, body=b"Hello, world!")13 assert response.status_code == 20014- assert response.reason == "OK"14+ assert response.reason_phrase == "OK"15 assert response.body == b"Hello, world!"16 assert response.is_closed17 18 51 unmodified lines70 71 def test_unknown_status_code():72 response = httpcore.Response(600)73 assert response.status_code == 60074- assert response.reason == ""74+ assert response.reason_phrase == ""