Skip to content
Myr

models.py

This file

Path

httpcore/models.py

401 lines · 12.1 KiB · Python

Last changed by

response.next()Tom Christiebefore adoptiond652479

History of this file

Take it

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 1–344why, one step back
1import http
2import 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, StreamConsumed14from .utils import normalize_header_key, normalize_header_value151617class 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 fragment(self) -> str:45 return self.components.fragment4647 @property48 def hostname(self) -> str:49 return self.components.hostname5051 @property52 def port(self) -> int:53 port = self.components.port54 if port is None:55 return {"https": 443, "http": 80}[self.scheme]56 return port5758 @property59 def full_path(self) -> str:60 path = self.path or "/"61 query = self.query62 if query:63 return path + "?" + query64 return path6566 @property67 def is_secure(self) -> bool:68 return self.components.scheme == "https"6970 @property71 def origin(self) -> "Origin":72 return Origin(self)7374 def __hash__(self) -> int:75 return hash(str(self))7677 def __eq__(self, other: typing.Any) -> bool:78 return isinstance(other, URL) and str(self) == str(other)7980 def __str__(self) -> str:81 return self.components.geturl()8283 def __repr__(self) -> str:84 class_name = self.__class__.__name__85 url_str = str(self)86 return f"{class_name}({url_str!r})"878889class Origin:90 def __init__(self, url: typing.Union[str, URL]) -> None:91 if isinstance(url, str):92 url = URL(url)93 self.is_ssl = url.scheme == "https"94 self.hostname = url.hostname.lower()95 self.port = url.port9697 def __eq__(self, other: typing.Any) -> bool:98 return (99 isinstance(other, self.__class__)100 and self.is_ssl == other.is_ssl101 and self.hostname == other.hostname102 and self.port == other.port103 )104105 def __hash__(self) -> int:106 return hash((self.is_ssl, self.hostname, self.port))107108109HeaderTypes = typing.Union[110 "Headers",111 typing.Dict[typing.AnyStr, typing.AnyStr],112 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],113]114115116class Headers(typing.MutableMapping[str, str]):117 """118 A case-insensitive multidict.119 """120121 def __init__(self, headers: HeaderTypes = None) -> None:122 if headers is None:123 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]124 elif isinstance(headers, Headers):125 self._list = list(headers.raw)126 elif isinstance(headers, dict):127 self._list = [128 (normalize_header_key(k), normalize_header_value(v))129 for k, v in headers.items()130 ]131 else:132 self._list = [133 (normalize_header_key(k), normalize_header_value(v)) for k, v in headers134 ]135136 @property137 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:138 return self._list139140 def keys(self) -> typing.List[str]: # type: ignore141 return [key.decode("latin-1") for key, value in self._list]142143 def values(self) -> typing.List[str]: # type: ignore144 return [value.decode("latin-1") for key, value in self._list]145146 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore147 return [148 (key.decode("latin-1"), value.decode("latin-1"))149 for key, value in self._list150 ]151152 def get(self, key: str, default: typing.Any = None) -> typing.Any:153 try:154 return self[key]155 except KeyError:156 return default157158 def getlist(self, key: str) -> typing.List[str]:159 get_header_key = key.lower().encode("latin-1")160 return [161 item_value.decode("latin-1")162 for item_key, item_value in self._list163 if item_key == get_header_key164 ]165166 def __getitem__(self, key: str) -> str:167 get_header_key = key.lower().encode("latin-1")168 for header_key, header_value in self._list:169 if header_key == get_header_key:170 return header_value.decode("latin-1")171 raise KeyError(key)172173 def __setitem__(self, key: str, value: str) -> None:174 """175 Set the header `key` to `value`, removing any duplicate entries.176 Retains insertion order.177 """178 set_key = key.lower().encode("latin-1")179 set_value = value.encode("latin-1")180181 found_indexes = []182 for idx, (item_key, item_value) in enumerate(self._list):183 if item_key == set_key:184 found_indexes.append(idx)185186 for idx in reversed(found_indexes[1:]):187 del self._list[idx]188189 if found_indexes:190 idx = found_indexes[0]191 self._list[idx] = (set_key, set_value)192 else:193 self._list.append((set_key, set_value))194195 def __delitem__(self, key: str) -> None:196 """197 Remove the header `key`.198 """199 del_key = key.lower().encode("latin-1")200201 pop_indexes = []202 for idx, (item_key, item_value) in enumerate(self._list):203 if item_key == del_key:204 pop_indexes.append(idx)205206 for idx in reversed(pop_indexes):207 del self._list[idx]208209 def __contains__(self, key: typing.Any) -> bool:210 get_header_key = key.lower().encode("latin-1")211 for header_key, header_value in self._list:212 if header_key == get_header_key:213 return True214 return False215216 def __iter__(self) -> typing.Iterator[typing.Any]:217 return iter(self.keys())218219 def __len__(self) -> int:220 return len(self._list)221222 def __eq__(self, other: typing.Any) -> bool:223 if not isinstance(other, Headers):224 return False225 return sorted(self._list) == sorted(other._list)226227 def __repr__(self) -> str:228 class_name = self.__class__.__name__229 as_dict = dict(self.items())230 if len(as_dict) == len(self):231 return f"{class_name}({as_dict!r})"232 return f"{class_name}(raw={self.raw!r})"233234235class Request:236 def __init__(237 self,238 method: str,239 url: typing.Union[str, URL],240 *,241 headers: HeaderTypes = None,242 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",243 ):244 self.method = method.upper()245 self.url = URL(url) if isinstance(url, str) else url246 if isinstance(body, bytes):247 self.is_streaming = False248 self.body = body249 else:250 self.is_streaming = True251 self.body_aiter = body252 self.headers = Headers(headers)253254 async def read(self) -> bytes:255 """256 Read and return the response content.257 """258 if not hasattr(self, "body"):259 body = b""260 async for part in self.stream():261 body += part262 self.body = body263 return self.body264265 async def stream(self) -> typing.AsyncIterator[bytes]:266 if self.is_streaming:267 async for part in self.body_aiter:268 yield part269 elif self.body:270 yield self.body271272 def prepare(self) -> None:273 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]274275 has_host = "host" in self.headers276 has_content_length = (277 "content-length" in self.headers or "transfer-encoding" in self.headers278 )279 has_accept_encoding = "accept-encoding" in self.headers280281 if not has_host:282 auto_headers.append((b"host", self.url.netloc.encode("ascii")))283 if not has_content_length:284 if self.is_streaming:285 auto_headers.append((b"transfer-encoding", b"chunked"))286 elif self.body:287 content_length = str(len(self.body)).encode()288 auto_headers.append((b"content-length", content_length))289 if not has_accept_encoding:290 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))291292 for item in reversed(auto_headers):293 self.headers.raw.insert(0, item)294295296class Response:297 def __init__(298 self,299 status_code: int,300 *,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"",305 on_close: typing.Callable = None,306 request: Request = None,307 history: typing.List["Response"] = None,308 ):309 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 = ""315 else:316 self.reason = reason317 self.protocol = protocol318 self.headers = Headers(headers)319 self.on_close = on_close320 self.is_closed = False321 self.is_streamed = False322323 decoders = [] # type: typing.List[Decoder]324 value = self.headers.get("content-encoding", "identity")325 for part in value.split(","):326 part = part.strip().lower()327 decoder_cls = SUPPORTED_DECODERS[part]328 decoders.append(decoder_cls())329330 if len(decoders) == 0:331 self.decoder = IdentityDecoder() # type: Decoder332 elif len(decoders) == 1:333 self.decoder = decoders[0]334 else:335 self.decoder = MultiDecoder(decoders)336337 if isinstance(body, bytes):338 self.is_closed = True339 self.body = self.decoder.decode(body) + self.decoder.flush()340 else:341 self.body_aiter = body342343 self.request = request344 self.history = [] if history is None else list(history)

response.next()Tom Christiebefore adoptiond652479

line 345why, one step back
345 self.next = None # typing.Optional[typing.Callable]

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 346–401why, one step back
346
347 @property348 def url(self) -> typing.Optional[URL]:349 return None if self.request is None else self.request.url350351 async def read(self) -> bytes:352 """353 Read and return the response content.354 """355 if not hasattr(self, "body"):356 body = b""357 async for part in self.stream():358 body += part359 self.body = body360 return self.body361362 async def stream(self) -> typing.AsyncIterator[bytes]:363 """364 A byte-iterator over the decoded response content.365 This allows us to handle gzip, deflate, and brotli encoded responses.366 """367 if hasattr(self, "body"):368 yield self.body369 else:370 async for chunk in self.raw():371 yield self.decoder.decode(chunk)372 yield self.decoder.flush()373374 async def raw(self) -> typing.AsyncIterator[bytes]:375 """376 A byte-iterator over the raw response content.377 """378 if self.is_streamed:379 raise StreamConsumed()380 if self.is_closed:381 raise ResponseClosed()382 self.is_streamed = True383 async for part in self.body_aiter:384 yield part385 await self.close()386387 async def close(self) -> None:388 """389 Close the response and release the connection.390 Automatically called if the response body is read to completion.391 """392 if not self.is_closed:393 self.is_closed = True394 if self.on_close is not None:395 await self.on_close()396397 @property398 def is_redirect(self) -> bool:399 return (400 self.status_code in (301, 302, 303, 307, 308) and "location" in self.headers401 )