models.py
This file
Path
httpcore/models.py
361 lines · 10.9 KiB · Python
Last changed by
RedirectionsTom Christiebefore adoption041813b
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)72RedirectionsTom Christiebefore adoption041813b
lines 73–78why, one step back73 def __hash__(self) -> int:74 return hash(str(self))7576 def __eq__(self, other: typing.Any) -> bool:77 return isinstance(other, URL) and str(self) == str(other)78RestructuringTom Christiebefore adoptione09fc37
lines 79–81why, one step back79 def __str__(self) -> str:80 return self.components.geturl()81Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 82–102why, one step back8283class Origin:84 def __init__(self, url: typing.Union[str, URL]) -> None:85 if isinstance(url, str):86 url = URL(url)87 self.is_ssl = url.scheme == "https"88 self.hostname = url.hostname.lower()89 self.port = url.port9091 def __eq__(self, other: typing.Any) -> bool:92 return (93 isinstance(other, self.__class__)94 and self.is_ssl == other.is_ssl95 and self.hostname == other.hostname96 and self.port == other.port97 )9899 def __hash__(self) -> int:100 return hash((self.is_ssl, self.hostname, self.port))101102Rollin'Tom Christiebefore adoption8a29a0a
lines 103–209why, one step back103class Headers(typing.MutableMapping[str, str]):104 """105 A case-insensitive multidict.106 """107108 def __init__(self, headers: typing.List[typing.Tuple[bytes, bytes]]) -> None:109 self._list = [(k.lower(), v) for k, v in headers]110111 @property112 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:113 return self._list114115 def keys(self) -> typing.List[str]: # type: ignore116 return [key.decode("latin-1") for key, value in self._list]117118 def values(self) -> typing.List[str]: # type: ignore119 return [value.decode("latin-1") for key, value in self._list]120121 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore122 return [123 (key.decode("latin-1"), value.decode("latin-1"))124 for key, value in self._list125 ]126127 def get(self, key: str, default: typing.Any = None) -> typing.Any:128 try:129 return self[key]130 except KeyError:131 return default132133 def getlist(self, key: str) -> typing.List[str]:134 get_header_key = key.lower().encode("latin-1")135 return [136 item_value.decode("latin-1")137 for item_key, item_value in self._list138 if item_key == get_header_key139 ]140141 def __getitem__(self, key: str) -> str:142 get_header_key = key.lower().encode("latin-1")143 for header_key, header_value in self._list:144 if header_key == get_header_key:145 return header_value.decode("latin-1")146 raise KeyError(key)147148 def __setitem__(self, key: str, value: str) -> None:149 """150 Set the header `key` to `value`, removing any duplicate entries.151 Retains insertion order.152 """153 set_key = key.lower().encode("latin-1")154 set_value = value.encode("latin-1")155156 found_indexes = []157 for idx, (item_key, item_value) in enumerate(self._list):158 if item_key == set_key:159 found_indexes.append(idx)160161 for idx in reversed(found_indexes[1:]):162 del self._list[idx]163164 if found_indexes:165 idx = found_indexes[0]166 self._list[idx] = (set_key, set_value)167 else:168 self._list.append((set_key, set_value))169170 def __delitem__(self, key: str) -> None:171 """172 Remove the header `key`.173 """174 del_key = key.lower().encode("latin-1")175176 pop_indexes = []177 for idx, (item_key, item_value) in enumerate(self._list):178 if item_key == del_key:179 pop_indexes.append(idx)180181 for idx in reversed(pop_indexes):182 del self._list[idx]183184 def __contains__(self, key: typing.Any) -> bool:185 get_header_key = key.lower().encode("latin-1")186 for header_key, header_value in self._list:187 if header_key == get_header_key:188 return True189 return False190191 def __iter__(self) -> typing.Iterator[typing.Any]:192 return iter(self.keys())193194 def __len__(self) -> int:195 return len(self._list)196197 def __eq__(self, other: typing.Any) -> bool:198 if not isinstance(other, Headers):199 return False200 return sorted(self._list) == sorted(other._list)201202 def __repr__(self) -> str:203 class_name = self.__class__.__name__204 as_dict = dict(self.items())205 if len(as_dict) == len(self):206 return f"{class_name}({as_dict!r})"207 return f"{class_name}(raw={self.raw!r})"208209Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 210–215why, one step back210class Request:211 def __init__(212 self,213 method: str,214 url: typing.Union[str, URL],215 *,Rollin'Tom Christiebefore adoption8a29a0a
line 216why, one step back216 headers: typing.List[typing.Tuple[bytes, bytes]] = [],Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 217–226why, one step back217 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",218 ):219 self.method = method.upper()220 self.url = URL(url) if isinstance(url, str) else url221 if isinstance(body, bytes):222 self.is_streaming = False223 self.body = body224 else:225 self.is_streaming = True226 self.body_aiter = bodyRollin'Tom Christiebefore adoption8a29a0a
line 227why, one step back227 self.headers = self.build_headers(headers)Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
line 228why, one step back228Rollin'Tom Christiebefore adoption8a29a0a
lines 229–231why, one step back229 def build_headers(230 self, init_headers: typing.List[typing.Tuple[bytes, bytes]]231 ) -> Headers:Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 232–235why, one step back232 has_host = False233 has_content_length = False234 has_accept_encoding = False235Rollin'Tom Christiebefore adoption8a29a0a
line 236why, one step back236 for header, value in init_headers:Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 237–244why, one step back237 header = header.strip().lower()238 if header == b"host":239 has_host = True240 elif header in (b"content-length", b"transfer-encoding"):241 has_content_length = True242 elif header == b"accept-encoding":243 has_accept_encoding = True244Rollin'Tom Christiebefore adoption8a29a0a
line 245why, one step back245 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 246–247why, one step back246247 if not has_host:Rollin'Tom Christiebefore adoption8a29a0a
line 248why, one step back248 auto_headers.append((b"host", self.url.netloc.encode("ascii")))Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 249–250why, one step back249 if not has_content_length:250 if self.is_streaming:Rollin'Tom Christiebefore adoption8a29a0a
line 251why, one step back251 auto_headers.append((b"transfer-encoding", b"chunked"))Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 252–253why, one step back252 elif self.body:253 content_length = str(len(self.body)).encode()Rollin'Tom Christiebefore adoption8a29a0a
line 254why, one step back254 auto_headers.append((b"content-length", content_length))Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
line 255why, one step back255 if not has_accept_encoding:Rollin'Tom Christiebefore adoption8a29a0a
line 256why, one step back256 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
line 257why, one step back257Rollin'Tom Christiebefore adoption8a29a0a
line 258why, one step back258 return Headers(auto_headers + init_headers)Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 259–274why, one step back259260 async def stream(self) -> typing.AsyncIterator[bytes]:261 if self.is_streaming:262 async for part in self.body_aiter:263 yield part264 elif self.body:265 yield self.body266267268class Response:269 def __init__(270 self,271 status_code: int,272 *,273 reason: typing.Optional[str] = None,274 protocol: typing.Optional[str] = None,Rollin'Tom Christiebefore adoption8a29a0a
line 275why, one step back275 headers: typing.List[typing.Tuple[bytes, bytes]] = [],Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 276–287why, one step back276 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",277 on_close: typing.Callable = None,278 ):279 self.status_code = status_code280 if not reason:281 try:282 self.reason = http.HTTPStatus(status_code).phrase283 except ValueError as exc:284 self.reason = ""285 else:286 self.reason = reason287 self.protocol = protocolRollin'Tom Christiebefore adoption8a29a0a
line 288why, one step back288 self.headers = Headers(headers)Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 289–293why, one step back289 self.on_close = on_close290 self.is_closed = False291 self.is_streamed = False292293 decoders = [] # type: typing.List[Decoder]Rollin'Tom Christiebefore adoption8a29a0a
lines 294–298why, one step back294 value = self.headers.get("content-encoding", "identity")295 for part in value.split(","):296 part = part.strip().lower()297 decoder_cls = SUPPORTED_DECODERS[part]298 decoders.append(decoder_cls())Add stream ID to HTTP2ConnectionTom Christiebefore adoption0bdcbae
lines 299–358why, one step back299300 if len(decoders) == 0:301 self.decoder = IdentityDecoder() # type: Decoder302 elif len(decoders) == 1:303 self.decoder = decoders[0]304 else:305 self.decoder = MultiDecoder(decoders)306307 if isinstance(body, bytes):308 self.is_closed = True309 self.body = self.decoder.decode(body) + self.decoder.flush()310 else:311 self.body_aiter = body312313 async def read(self) -> bytes:314 """315 Read and return the response content.316 """317 if not hasattr(self, "body"):318 body = b""319 async for part in self.stream():320 body += part321 self.body = body322 return self.body323324 async def stream(self) -> typing.AsyncIterator[bytes]:325 """326 A byte-iterator over the decoded response content.327 This allows us to handle gzip, deflate, and brotli encoded responses.328 """329 if hasattr(self, "body"):330 yield self.body331 else:332 async for chunk in self.raw():333 yield self.decoder.decode(chunk)334 yield self.decoder.flush()335336 async def raw(self) -> typing.AsyncIterator[bytes]:337 """338 A byte-iterator over the raw response content.339 """340 if self.is_streamed:341 raise StreamConsumed()342 if self.is_closed:343 raise ResponseClosed()344 self.is_streamed = True345 async for part in self.body_aiter:346 yield part347 await self.close()348349 async def close(self) -> None:350 """351 Close the response and release the connection.352 Automatically called if the response body is read to completion.353 """354 if not self.is_closed:355 self.is_closed = True356 if self.on_close is not None:357 await self.on_close()358AdaptersTom Christiebefore adoptionfab6fcd
lines 359–361why, one step back359 @property360 def is_redirect(self) -> bool:361 return self.status_code in (301, 302, 303, 307, 308)