models.py
This file
Path
httpcore/models.py
355 lines · 10.7 KiB · Python
Last changed by
RestructuringTom Christiebefore adoptione09fc37
History of this fileTake it
Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 1–42why, one step back1import http2import typing3from urllib.parse import urlsplit45from .config import SSLConfig, TimeoutConfig6from .decoders import (7 ACCEPT_ENCODING,8 SUPPORTED_DECODERS,9 Decoder,10 IdentityDecoder,11 MultiDecoder,12)13from .exceptions import ResponseClosed, StreamConsumed141516class URL:17 def __init__(self, url: str = "") -> None:18 self.components = urlsplit(url)19 if not self.components.scheme:20 raise ValueError("No scheme included in URL.")21 if self.components.scheme not in ("http", "https"):22 raise ValueError('URL scheme must be "http" or "https".')23 if not self.components.hostname:24 raise ValueError("No hostname included in URL.")2526 @property27 def scheme(self) -> str:28 return self.components.scheme2930 @property31 def netloc(self) -> str:32 return self.components.netloc3334 @property35 def path(self) -> str:36 return self.components.path3738 @property39 def query(self) -> str:40 return self.components.query4142 @propertyRollin'Tom Christiebefore adoption8a29a0a
lines 43–46why, one step back43 def fragment(self) -> str:44 return self.components.fragment4546 @propertyAdd stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 47–72why, one step back47 def hostname(self) -> str:48 return self.components.hostname4950 @property51 def port(self) -> int:52 port = self.components.port53 if port is None:54 return {"https": 443, "http": 80}[self.scheme]55 return port5657 @property58 def full_path(self) -> str:59 path = self.path or "/"60 query = self.query61 if query:62 return path + "?" + query63 return path6465 @property66 def is_secure(self) -> bool:67 return self.components.scheme == "https"6869 @property70 def origin(self) -> "Origin":71 return Origin(self)72RestructuringTom Christiebefore adoptione09fc37
lines 73–75why, one step back73 def __str__(self) -> str:74 return self.components.geturl()75Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 76–96why, one step back7677class Origin:78 def __init__(self, url: typing.Union[str, URL]) -> None:79 if isinstance(url, str):80 url = URL(url)81 self.is_ssl = url.scheme == "https"82 self.hostname = url.hostname.lower()83 self.port = url.port8485 def __eq__(self, other: typing.Any) -> bool:86 return (87 isinstance(other, self.__class__)88 and self.is_ssl == other.is_ssl89 and self.hostname == other.hostname90 and self.port == other.port91 )9293 def __hash__(self) -> int:94 return hash((self.is_ssl, self.hostname, self.port))9596Rollin'Tom Christiebefore adoption8a29a0a
lines 97–203why, one step back97class Headers(typing.MutableMapping[str, str]):98 """99 A case-insensitive multidict.100 """101102 def __init__(self, headers: typing.List[typing.Tuple[bytes, bytes]]) -> None:103 self._list = [(k.lower(), v) for k, v in headers]104105 @property106 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:107 return self._list108109 def keys(self) -> typing.List[str]: # type: ignore110 return [key.decode("latin-1") for key, value in self._list]111112 def values(self) -> typing.List[str]: # type: ignore113 return [value.decode("latin-1") for key, value in self._list]114115 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore116 return [117 (key.decode("latin-1"), value.decode("latin-1"))118 for key, value in self._list119 ]120121 def get(self, key: str, default: typing.Any = None) -> typing.Any:122 try:123 return self[key]124 except KeyError:125 return default126127 def getlist(self, key: str) -> typing.List[str]:128 get_header_key = key.lower().encode("latin-1")129 return [130 item_value.decode("latin-1")131 for item_key, item_value in self._list132 if item_key == get_header_key133 ]134135 def __getitem__(self, key: str) -> str:136 get_header_key = key.lower().encode("latin-1")137 for header_key, header_value in self._list:138 if header_key == get_header_key:139 return header_value.decode("latin-1")140 raise KeyError(key)141142 def __setitem__(self, key: str, value: str) -> None:143 """144 Set the header `key` to `value`, removing any duplicate entries.145 Retains insertion order.146 """147 set_key = key.lower().encode("latin-1")148 set_value = value.encode("latin-1")149150 found_indexes = []151 for idx, (item_key, item_value) in enumerate(self._list):152 if item_key == set_key:153 found_indexes.append(idx)154155 for idx in reversed(found_indexes[1:]):156 del self._list[idx]157158 if found_indexes:159 idx = found_indexes[0]160 self._list[idx] = (set_key, set_value)161 else:162 self._list.append((set_key, set_value))163164 def __delitem__(self, key: str) -> None:165 """166 Remove the header `key`.167 """168 del_key = key.lower().encode("latin-1")169170 pop_indexes = []171 for idx, (item_key, item_value) in enumerate(self._list):172 if item_key == del_key:173 pop_indexes.append(idx)174175 for idx in reversed(pop_indexes):176 del self._list[idx]177178 def __contains__(self, key: typing.Any) -> bool:179 get_header_key = key.lower().encode("latin-1")180 for header_key, header_value in self._list:181 if header_key == get_header_key:182 return True183 return False184185 def __iter__(self) -> typing.Iterator[typing.Any]:186 return iter(self.keys())187188 def __len__(self) -> int:189 return len(self._list)190191 def __eq__(self, other: typing.Any) -> bool:192 if not isinstance(other, Headers):193 return False194 return sorted(self._list) == sorted(other._list)195196 def __repr__(self) -> str:197 class_name = self.__class__.__name__198 as_dict = dict(self.items())199 if len(as_dict) == len(self):200 return f"{class_name}({as_dict!r})"201 return f"{class_name}(raw={self.raw!r})"202203Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 204–209why, one step back204class Request:205 def __init__(206 self,207 method: str,208 url: typing.Union[str, URL],209 *,Rollin'Tom Christiebefore adoption8a29a0a
line 210why, one step back210 headers: typing.List[typing.Tuple[bytes, bytes]] = [],Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 211–220why, one step back211 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",212 ):213 self.method = method.upper()214 self.url = URL(url) if isinstance(url, str) else url215 if isinstance(body, bytes):216 self.is_streaming = False217 self.body = body218 else:219 self.is_streaming = True220 self.body_aiter = bodyRollin'Tom Christiebefore adoption8a29a0a
line 221why, one step back221 self.headers = self.build_headers(headers)Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
line 222why, one step back222Rollin'Tom Christiebefore adoption8a29a0a
lines 223–225why, one step back223 def build_headers(224 self, init_headers: typing.List[typing.Tuple[bytes, bytes]]225 ) -> Headers:Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 226–229why, one step back226 has_host = False227 has_content_length = False228 has_accept_encoding = False229Rollin'Tom Christiebefore adoption8a29a0a
line 230why, one step back230 for header, value in init_headers:Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 231–238why, one step back231 header = header.strip().lower()232 if header == b"host":233 has_host = True234 elif header in (b"content-length", b"transfer-encoding"):235 has_content_length = True236 elif header == b"accept-encoding":237 has_accept_encoding = True238Rollin'Tom Christiebefore adoption8a29a0a
line 239why, one step back239 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 240–241why, one step back240241 if not has_host:Rollin'Tom Christiebefore adoption8a29a0a
line 242why, one step back242 auto_headers.append((b"host", self.url.netloc.encode("ascii")))Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 243–244why, one step back243 if not has_content_length:244 if self.is_streaming:Rollin'Tom Christiebefore adoption8a29a0a
line 245why, one step back245 auto_headers.append((b"transfer-encoding", b"chunked"))Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 246–247why, one step back246 elif self.body:247 content_length = str(len(self.body)).encode()Rollin'Tom Christiebefore adoption8a29a0a
line 248why, one step back248 auto_headers.append((b"content-length", content_length))Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
line 249why, one step back249 if not has_accept_encoding:Rollin'Tom Christiebefore adoption8a29a0a
line 250why, one step back250 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
line 251why, one step back251Rollin'Tom Christiebefore adoption8a29a0a
line 252why, one step back252 return Headers(auto_headers + init_headers)Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 253–268why, one step back253254 async def stream(self) -> typing.AsyncIterator[bytes]:255 if self.is_streaming:256 async for part in self.body_aiter:257 yield part258 elif self.body:259 yield self.body260261262class Response:263 def __init__(264 self,265 status_code: int,266 *,267 reason: typing.Optional[str] = None,268 protocol: typing.Optional[str] = None,Rollin'Tom Christiebefore adoption8a29a0a
line 269why, one step back269 headers: typing.List[typing.Tuple[bytes, bytes]] = [],Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 270–281why, one step back270 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",271 on_close: typing.Callable = None,272 ):273 self.status_code = status_code274 if not reason:275 try:276 self.reason = http.HTTPStatus(status_code).phrase277 except ValueError as exc:278 self.reason = ""279 else:280 self.reason = reason281 self.protocol = protocolRollin'Tom Christiebefore adoption8a29a0a
line 282why, one step back282 self.headers = Headers(headers)Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 283–287why, one step back283 self.on_close = on_close284 self.is_closed = False285 self.is_streamed = False286287 decoders = [] # type: typing.List[Decoder]Rollin'Tom Christiebefore adoption8a29a0a
lines 288–292why, one step back288 value = self.headers.get("content-encoding", "identity")289 for part in value.split(","):290 part = part.strip().lower()291 decoder_cls = SUPPORTED_DECODERS[part]292 decoders.append(decoder_cls())Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 293–352why, one step back293294 if len(decoders) == 0:295 self.decoder = IdentityDecoder() # type: Decoder296 elif len(decoders) == 1:297 self.decoder = decoders[0]298 else:299 self.decoder = MultiDecoder(decoders)300301 if isinstance(body, bytes):302 self.is_closed = True303 self.body = self.decoder.decode(body) + self.decoder.flush()304 else:305 self.body_aiter = body306307 async def read(self) -> bytes:308 """309 Read and return the response content.310 """311 if not hasattr(self, "body"):312 body = b""313 async for part in self.stream():314 body += part315 self.body = body316 return self.body317318 async def stream(self) -> typing.AsyncIterator[bytes]:319 """320 A byte-iterator over the decoded response content.321 This allows us to handle gzip, deflate, and brotli encoded responses.322 """323 if hasattr(self, "body"):324 yield self.body325 else:326 async for chunk in self.raw():327 yield self.decoder.decode(chunk)328 yield self.decoder.flush()329330 async def raw(self) -> typing.AsyncIterator[bytes]:331 """332 A byte-iterator over the raw response content.333 """334 if self.is_streamed:335 raise StreamConsumed()336 if self.is_closed:337 raise ResponseClosed()338 self.is_streamed = True339 async for part in self.body_aiter:340 yield part341 await self.close()342343 async def close(self) -> None:344 """345 Close the response and release the connection.346 Automatically called if the response body is read to completion.347 """348 if not self.is_closed:349 self.is_closed = True350 if self.on_close is not None:351 await self.on_close()352AdaptersTom Christiebefore adoptionfab6fcd
lines 353–355why, one step back353 @property354 def is_redirect(self) -> bool:355 return self.status_code in (301, 302, 303, 307, 308)