Skip to content
Myr

datastructures.py

This file

Path

httpcore/datastructures.py

284 lines · 8.3 KiB · Python

Last changed by

Merge pull request #12 from encode/refactorTom Christiebefore adoption39eb55b

History of this file

Take it

Add response.reasonTom Christiebefore adoptionfc7cf9d

line 1why, one step back
1import http

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

line 2why, one step back
2import typing

Merge pull request #12 from encode/refactorTom Christiebefore adoption39eb55b

line 3why, one step back
3from types import TracebackType

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 4–5why, one step back
4from urllib.parse import urlsplit
5

Merge pull request #12 from encode/refactorTom Christiebefore adoption39eb55b

line 6why, one step back
6from .config import SSLConfig, TimeoutConfig

Merge pull request #3 from encode/request-auto-headersTom Christiebefore adoptionfae53e2

lines 7–13why, one step back
7from .decoders import (
8 ACCEPT_ENCODING,9 SUPPORTED_DECODERS,10 Decoder,11 IdentityDecoder,12 MultiDecoder,13)

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 14–65why, one step back
14from .exceptions import ResponseClosed, StreamConsumed
151617class URL:18 def __init__(self, url: str = "") -> None:19 self.components = urlsplit(url)20 if not self.components.scheme:21 raise ValueError("No scheme included in URL.")22 if self.components.scheme not in ("http", "https"):23 raise ValueError('URL scheme must be "http" or "https".')24 if not self.components.hostname:25 raise ValueError("No hostname included in URL.")2627 @property28 def scheme(self) -> str:29 return self.components.scheme3031 @property32 def netloc(self) -> str:33 return self.components.netloc3435 @property36 def path(self) -> str:37 return self.components.path3839 @property40 def query(self) -> str:41 return self.components.query4243 @property44 def hostname(self) -> str:45 return self.components.hostname4647 @property48 def port(self) -> int:49 port = self.components.port50 if port is None:51 return {"https": 443, "http": 80}[self.scheme]52 return port5354 @property55 def target(self) -> str:56 path = self.path or "/"57 query = self.query58 if query:59 return path + "?" + query60 return path6162 @property63 def is_secure(self) -> bool:64 return self.components.scheme == "https"65

Merge pull request #12 from encode/refactorTom Christiebefore adoption39eb55b

lines 66–68why, one step back
66 @property
67 def origin(self) -> "Origin":68 return Origin(self)

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

line 69why, one step back
69

Merge pull request #12 from encode/refactorTom Christiebefore adoption39eb55b

lines 70–94why, one step back
70
71class Origin:72 def __init__(self, url: typing.Union[str, URL]) -> None:73 if isinstance(url, str):74 url = URL(url)75 self.scheme = url.scheme76 self.hostname = url.hostname77 self.port = url.port7879 @property80 def is_secure(self) -> bool:81 return self.scheme == "https"8283 def __eq__(self, other: typing.Any) -> bool:84 return (85 isinstance(other, self.__class__)86 and self.scheme == other.scheme87 and self.hostname == other.hostname88 and self.port == other.port89 )9091 def __hash__(self) -> int:92 return hash((self.scheme, self.hostname, self.port))9394

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 95–98why, one step back
95class Request:
96 def __init__(97 self,98 method: str,

Merge pull request #3 from encode/request-auto-headersTom Christiebefore adoptionfae53e2

line 99why, one step back
99 url: typing.Union[str, URL],

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 100–104why, one step back
100 *,
101 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),102 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",103 ):104 self.method = method

Merge pull request #3 from encode/request-auto-headersTom Christiebefore adoptionfae53e2

line 105why, one step back
105 self.url = URL(url) if isinstance(url, str) else url

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 106–112why, one step back
106 self.headers = list(headers)
107 if isinstance(body, bytes):108 self.is_streaming = False109 self.body = body110 else:111 self.is_streaming = True112 self.body_aiter = body

Merge pull request #3 from encode/request-auto-headersTom Christiebefore adoptionfae53e2

line 113why, one step back
113 self.headers = self._auto_headers() + self.headers

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

line 114why, one step back
114

Merge pull request #3 from encode/request-auto-headersTom Christiebefore adoptionfae53e2

lines 115–143why, one step back
115 def _auto_headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:
116 has_host = False117 has_content_length = False118 has_accept_encoding = False119120 for header, value in self.headers:121 header = header.strip().lower()122 if header == b"host":123 has_host = True124 elif header in (b"content-length", b"transfer-encoding"):125 has_content_length = True126 elif header == b"accept-encoding":127 has_accept_encoding = True128129 headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]130131 if not has_host:132 headers.append((b"host", self.url.netloc.encode("ascii")))133 if not has_content_length:134 if self.is_streaming:135 headers.append((b"transfer-encoding", b"chunked"))136 elif self.body:137 content_length = str(len(self.body)).encode()138 headers.append((b"content-length", content_length))139 if not has_accept_encoding:140 headers.append((b"accept-encoding", ACCEPT_ENCODING))141142 return headers143

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 144–155why, one step back
144 async def stream(self) -> typing.AsyncIterator[bytes]:
145 assert self.is_streaming146147 async for part in self.body_aiter:148 yield part149150151class Response:152 def __init__(153 self,154 status_code: int,155 *,

Add response.reasonTom Christiebefore adoptionfc7cf9d

line 156why, one step back
156 reason: typing.Optional[str] = None,

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 157–161why, one step back
157 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),
158 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",159 on_close: typing.Callable = None,160 ):161 self.status_code = status_code

Add response.reasonTom Christiebefore adoptionfc7cf9d

lines 162–168why, one step back
162 if not reason:
163 try:164 self.reason = http.HTTPStatus(status_code).phrase165 except ValueError as exc:166 self.reason = ""167 else:168 self.reason = reason

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 169–172why, one step back
169 self.headers = list(headers)
170 self.on_close = on_close171 self.is_closed = False172 self.is_streamed = False

Merge pull request #2 from encode/decompressionTom Christiebefore adoption60befed

lines 173–188why, one step back
173
174 decoders = [] # type: typing.List[Decoder]175 for header, value in self.headers:176 if header.strip().lower() == b"content-encoding":177 for part in value.split(b","):178 part = part.strip().lower()179 decoder_cls = SUPPORTED_DECODERS[part]180 decoders.append(decoder_cls())181182 if len(decoders) == 0:183 self.decoder = IdentityDecoder() # type: Decoder184 elif len(decoders) == 1:185 self.decoder = decoders[0]186 else:187 self.decoder = MultiDecoder(decoders)188

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 189–190why, one step back
189 if isinstance(body, bytes):
190 self.is_closed = True

Merge pull request #2 from encode/decompressionTom Christiebefore adoption60befed

line 191why, one step back
191 self.body = self.decoder.decode(body) + self.decoder.flush()

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 192–208why, one step back
192 else:
193 self.body_aiter = body194195 async def read(self) -> bytes:196 """197 Read and return the response content.198 """199 if not hasattr(self, "body"):200 body = b""201 async for part in self.stream():202 body += part203 self.body = body204 return self.body205206 async def stream(self) -> typing.AsyncIterator[bytes]:207 """208 A byte-iterator over the decoded response content.

Merge pull request #3 from encode/request-auto-headersTom Christiebefore adoptionfae53e2

line 209why, one step back
209 This allows us to handle gzip, deflate, and brotli encoded responses.

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 210–231why, one step back
210 """
211 if hasattr(self, "body"):212 yield self.body213 else:214 async for chunk in self.raw():215 yield self.decoder.decode(chunk)216 yield self.decoder.flush()217218 async def raw(self) -> typing.AsyncIterator[bytes]:219 """220 A byte-iterator over the raw response content.221 """222 if self.is_streamed:223 raise StreamConsumed()224 if self.is_closed:225 raise ResponseClosed()226 self.is_streamed = True227 async for part in self.body_aiter:228 yield part229 await self.close()230231 async def close(self) -> None:

Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a

lines 232–235why, one step back
232 """
233 Close the response and release the connection.234 Automatically called if the response body is read to completion.235 """

Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7

lines 236–239why, one step back
236 if not self.is_closed:
237 self.is_closed = True238 if self.on_close is not None:239 await self.on_close()

Merge pull request #12 from encode/refactorTom Christiebefore adoption39eb55b

lines 240–284why, one step back
240
241242class Client:243 async def request(244 self,245 method: str,246 url: typing.Union[str, URL],247 *,248 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),249 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",250 ssl: typing.Optional[SSLConfig] = None,251 timeout: typing.Optional[TimeoutConfig] = None,252 stream: bool = False,253 ) -> Response:254 request = Request(method, url, headers=headers, body=body)255 response = await self.send(request, ssl=ssl, timeout=timeout)256 if not stream:257 try:258 await response.read()259 finally:260 await response.close()261 return response262263 async def send(264 self,265 request: Request,266 *,267 ssl: typing.Optional[SSLConfig] = None,268 timeout: typing.Optional[TimeoutConfig] = None,269 ) -> Response:270 raise NotImplementedError() # pragma: nocover271272 async def close(self) -> None:273 raise NotImplementedError() # pragma: nocover274275 async def __aenter__(self) -> "Client":276 return self277278 async def __aexit__(279 self,280 exc_type: typing.Type[BaseException] = None,281 exc_value: BaseException = None,282 traceback: TracebackType = None,283 ) -> None:284 await self.close()