models.py
This file
Path
httpcore/models.py
629 lines · 19.7 KiB · Python
Last changed by
Fix docstringsTom Christiebefore adoption8a227c1
History of this fileTake it
1import cgi2import typing34import chardet5import idna6import rfc398678from .config import SSLConfig, TimeoutConfig9from .constants import codes10from .decoders import (11 ACCEPT_ENCODING,12 SUPPORTED_DECODERS,13 Decoder,14 IdentityDecoder,15 MultiDecoder,16)17from .exceptions import InvalidURL, ResponseClosed, ResponseNotRead, StreamConsumed18from .utils import (19 get_reason_phrase,20 is_known_encoding,21 normalize_header_key,22 normalize_header_value,23)2425URLTypes = typing.Union["URL", str]2627HeaderTypes = typing.Union[28 "Headers",29 typing.Dict[typing.AnyStr, typing.AnyStr],30 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],31]3233ByteOrByteStream = typing.Union[bytes, typing.AsyncIterator[bytes]]343536class URL:37 def __init__(self, url: URLTypes, allow_relative: bool = False) -> None:38 if isinstance(url, rfc3986.uri.URIReference):39 self.components = url40 elif isinstance(url, str):41 self.components = rfc3986.api.uri_reference(url)42 else:43 self.components = url.components4445 # Handle IDNA domain names.46 if self.components.authority:47 idna_authority = self.components.authority.encode("idna").decode("ascii")48 if idna_authority != self.components.authority:49 self.components = self.components.copy_with(authority=idna_authority)5051 # Normalize scheme and domain name.52 self.components = self.components.normalize()5354 # Enforce absolute URLs by default.55 if not allow_relative:56 if not self.scheme:57 raise InvalidURL("No scheme included in URL.")58 if self.scheme not in ("http", "https"):59 raise InvalidURL('URL scheme must be "http" or "https".')60 if not self.host:61 raise InvalidURL("No host included in URL.")6263 @property64 def scheme(self) -> str:65 return self.components.scheme or ""6667 @property68 def authority(self) -> str:69 return self.components.authority or ""7071 @property72 def host(self) -> str:73 return self.components.host or ""7475 @property76 def port(self) -> int:77 port = self.components.port78 if port is None:79 return {"https": 443, "http": 80}[self.scheme]80 return int(port)8182 @property83 def path(self) -> str:84 return self.components.path or "/"8586 @property87 def query(self) -> str:88 return self.components.query or ""8990 @property91 def full_path(self) -> str:92 path = self.path93 if self.query:94 path += "?" + self.query95 return path9697 @property98 def fragment(self) -> str:99 return self.components.fragment or ""100101 @property102 def is_ssl(self) -> bool:103 return self.components.scheme == "https"104105 @property106 def is_absolute_url(self) -> bool:107 """108 Return `True` for absolute URLs such as 'http://example.com/path',109 and `False` for relative URLs such as '/path'.110 """111 # We don't use rfc3986's `is_absolute` because it treats112 # URLs with a fragment portion as not absolute.113 # What we actually care about is if the URL provides114 # a scheme and hostname to which connections should be made.115 return self.components.scheme and self.components.host116117 @property118 def is_relative_url(self) -> bool:119 return not self.is_absolute_url120121 @property122 def origin(self) -> "Origin":123 return Origin(self)124125 def copy_with(self, **kwargs: typing.Any) -> "URL":126 return URL(self.components.copy_with(**kwargs))127128 def resolve_with(self, base_url: URLTypes) -> "URL":129 """130 Return an absolute URL, using base_url as the base.131 """132 # We drop any fragment portion, because RFC 3986 strictly133 # treats URLs with a fragment portion as not being absolute URLs.134 base_url = URL(base_url).copy_with(fragment=None)135 return URL(self.components.resolve_with(base_url.components))136137 def __hash__(self) -> int:138 return hash(str(self))139140 def __eq__(self, other: typing.Any) -> bool:141 return isinstance(other, URL) and str(self) == str(other)142143 def __str__(self) -> str:144 return self.components.unsplit()145146 def __repr__(self) -> str:147 class_name = self.__class__.__name__148 url_str = str(self)149 return f"{class_name}({url_str!r})"150151152class Origin:153 def __init__(self, url: URLTypes) -> None:154 if not isinstance(url, URL):155 url = URL(url)156 self.is_ssl = url.is_ssl157 self.host = url.host158 self.port = url.port159160 def __eq__(self, other: typing.Any) -> bool:161 return (162 isinstance(other, self.__class__)163 and self.is_ssl == other.is_ssl164 and self.host == other.host165 and self.port == other.port166 )167168 def __hash__(self) -> int:169 return hash((self.is_ssl, self.host, self.port))170171172class Headers(typing.MutableMapping[str, str]):173 """174 A case-insensitive multidict.175 """176177 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:178 if headers is None:179 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]180 elif isinstance(headers, Headers):181 self._list = list(headers.raw)182 elif isinstance(headers, dict):183 self._list = [184 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))185 for k, v in headers.items()186 ]187 else:188 self._list = [189 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))190 for k, v in headers191 ]192 self._encoding = encoding193194 @property195 def encoding(self) -> str:196 """197 Header encoding is mandated as ascii, but utf-8 or iso-8859-1 may be198 seen in the wild.199 """200 if self._encoding is None:201 for encoding in ["ascii", "utf-8"]:202 for key, value in self.raw:203 try:204 key.decode(encoding)205 value.decode(encoding)206 except UnicodeDecodeError:207 break208 else:209 # The else block runs if 'break' did not occur, meaning210 # all values fitted the encoding.211 self._encoding = encoding212 break213 else:214 # The ISO-8859-1 encoding covers all 256 code points in a byte,215 # so will never raise decode errors.216 self._encoding = "iso-8859-1"217 return self._encoding218219 @encoding.setter220 def encoding(self, value: str) -> None:221 self._encoding = value222223 @property224 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:225 """226 Returns a list of the raw header items, as byte pairs.227 May be mutated in-place.228 """229 return self._list230231 def keys(self) -> typing.List[str]: # type: ignore232 return [key.decode(self.encoding) for key, value in self._list]233234 def values(self) -> typing.List[str]: # type: ignore235 return [value.decode(self.encoding) for key, value in self._list]236237 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore238 return [239 (key.decode(self.encoding), value.decode(self.encoding))240 for key, value in self._list241 ]242243 def get(self, key: str, default: typing.Any = None) -> typing.Any:244 try:245 return self[key]246 except KeyError:247 return default248249 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:250 """251 Return multiple header values.252 """253 get_header_key = key.lower().encode(self.encoding)254255 values = [256 item_value.decode(self.encoding)257 for item_key, item_value in self._list258 if item_key == get_header_key259 ]260261 if not split_commas:262 return values263264 split_values = []265 for value in values:266 split_values.extend([item.strip() for item in value.split(",")])267 return split_values268269 def __getitem__(self, key: str) -> str:270 """271 Return a single header value.272273 If there are multiple headers with the same key, then we concatenate274 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2275 """276 normalized_key = key.lower().encode(self.encoding)277278 items = []279 for header_key, header_value in self._list:280 if header_key == normalized_key:281 items.append(header_value.decode(self.encoding))282283 if items:284 return ", ".join(items)285286 raise KeyError(key)287288 def __setitem__(self, key: str, value: str) -> None:289 """290 Set the header `key` to `value`, removing any duplicate entries.291 Retains insertion order.292 """293 set_key = key.lower().encode(self.encoding)294 set_value = value.encode(self.encoding)295296 found_indexes = []297 for idx, (item_key, item_value) in enumerate(self._list):298 if item_key == set_key:299 found_indexes.append(idx)300301 for idx in reversed(found_indexes[1:]):302 del self._list[idx]303304 if found_indexes:305 idx = found_indexes[0]306 self._list[idx] = (set_key, set_value)307 else:308 self._list.append((set_key, set_value))309310 def __delitem__(self, key: str) -> None:311 """312 Remove the header `key`.313 """314 del_key = key.lower().encode(self.encoding)315316 pop_indexes = []317 for idx, (item_key, item_value) in enumerate(self._list):318 if item_key == del_key:319 pop_indexes.append(idx)320321 for idx in reversed(pop_indexes):322 del self._list[idx]323324 def __contains__(self, key: typing.Any) -> bool:325 get_header_key = key.lower().encode(self.encoding)326 for header_key, header_value in self._list:327 if header_key == get_header_key:328 return True329 return False330331 def __iter__(self) -> typing.Iterator[typing.Any]:332 return iter(self.keys())333334 def __len__(self) -> int:335 return len(self._list)336337 def __eq__(self, other: typing.Any) -> bool:338 if not isinstance(other, Headers):339 return False340 return sorted(self._list) == sorted(other._list)341342 def __repr__(self) -> str:343 class_name = self.__class__.__name__344345 encoding_str = ""346 if self.encoding != "ascii":347 encoding_str = f", encoding={self.encoding!r}"348349 as_dict = dict(self.items())350 if len(as_dict) == len(self):351 return f"{class_name}({as_dict!r}{encoding_str})"352 as_list = self.items()353 return f"{class_name}({as_list!r}{encoding_str})"354355356class Request:357 def __init__(358 self,359 method: str,360 url: typing.Union[str, URL],361 *,362 headers: HeaderTypes = None,363 content: ByteOrByteStream = b"",364 ):365 self.method = method.upper()366 self.url = URL(url) if isinstance(url, str) else url367 if isinstance(content, bytes):368 self.is_streaming = False369 self.content = content370 else:371 self.is_streaming = True372 self.content_aiter = content373 self.headers = Headers(headers)374375 async def read(self) -> bytes:376 """377 Read and return the response content.378 """379 if not hasattr(self, "content"):380 content = b""381 async for part in self.stream():382 content += part383 self.content = content384 return self.content385386 async def stream(self) -> typing.AsyncIterator[bytes]:387 if self.is_streaming:388 async for part in self.content_aiter:389 yield part390 elif self.content:391 yield self.content392393 def prepare(self) -> None:394 """395 Adds in any default headers. When using the `Client`, this will396 end up being called into by the `prepare_request()` stage.397398 You can omit this behavior by calling `Client.send()` with an399 explicitly built `Request` instance.400 """401 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]402403 has_host = "host" in self.headers404 has_content_length = (405 "content-length" in self.headers or "transfer-encoding" in self.headers406 )407 has_accept_encoding = "accept-encoding" in self.headers408409 if not has_host and self.url.authority:410 auto_headers.append((b"host", self.url.authority.encode("ascii")))411 if not has_content_length:412 if self.is_streaming:413 auto_headers.append((b"transfer-encoding", b"chunked"))414 elif self.content:415 content_length = str(len(self.content)).encode()416 auto_headers.append((b"content-length", content_length))417 if not has_accept_encoding:418 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))419420 for item in reversed(auto_headers):421 self.headers.raw.insert(0, item)422423 def __repr__(self) -> str:424 class_name = self.__class__.__name__425 url = str(self.url)426 return f"<{class_name}({self.method}, {url})>"427428429class Response:430 def __init__(431 self,432 status_code: int,433 *,434 reason_phrase: str = None,435 protocol: str = None,436 headers: HeaderTypes = None,437 content: ByteOrByteStream = b"",438 on_close: typing.Callable = None,439 request: Request = None,440 history: typing.List["Response"] = None,441 ):442 try:443 # Use a StatusCode IntEnum if possible, for a nicer representation.444 self.status_code = codes(status_code) # type: int445 except ValueError:446 self.status_code = status_code447 self.reason_phrase = reason_phrase or get_reason_phrase(status_code)448 self.protocol = protocol449 self.headers = Headers(headers)450451 if isinstance(content, bytes):452 self.is_closed = True453 self.is_stream_consumed = True454 self._raw_content = content455 else:456 self.is_closed = False457 self.is_stream_consumed = False458 self._raw_stream = content459460 self.on_close = on_close461 self.request = request462 self.history = [] if history is None else list(history)463 self.next = None # typing.Optional[typing.Callable]464465 @property466 def url(self) -> typing.Optional[URL]:467 """468 Returns the URL for which the request was made.469470 Requires that `request` was provided when instantiating the response.471 """472 return None if self.request is None else self.request.url473474 @property475 def content(self) -> bytes:476 if not hasattr(self, "_content"):477 if hasattr(self, "_raw_content"):478 content = self.decoder.decode(self._raw_content)479 content += self.decoder.flush()480 self._content = content481 else:482 raise ResponseNotRead()483 return self._content484485 @property486 def text(self) -> str:487 if not hasattr(self, "_text"):488 content = self.content489 if not content:490 self._text = ""491 else:492 encoding = self.encoding493 self._text = content.decode(encoding, errors="replace")494 return self._text495496 @property497 def encoding(self) -> str:498 if not hasattr(self, "_encoding"):499 encoding = self.charset_encoding500 if encoding is None or not is_known_encoding(encoding):501 encoding = self.apparent_encoding502 if encoding is None or not is_known_encoding(encoding):503 encoding = "utf-8"504 self._encoding = encoding505 return self._encoding506507 @encoding.setter508 def encoding(self, value: str) -> None:509 self._encoding = value510511 @property512 def charset_encoding(self) -> typing.Optional[str]:513 """514 Return the encoding, as specified by the Content-Type header.515 """516 content_type = self.headers.get("Content-Type")517 if content_type is None:518 return None519520 parsed = cgi.parse_header(content_type)521 media_type, params = parsed[0], parsed[-1]522 if "charset" in params:523 return params["charset"].strip("'\"")524525 # RFC 2616 specifies that 'iso-8859-1' should be used as the default526 # for 'text/*' media types, if no charset is provided.527 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1528 if media_type.startswith("text/"):529 return "iso-8859-1"530531 return None532533 @property534 def apparent_encoding(self) -> typing.Optional[str]:535 """536 Return the encoding, as it appears to autodetection.537 """538 return chardet.detect(self.content)["encoding"]539540 @property541 def decoder(self) -> Decoder:542 """543 Returns a decoder instance which can be used to decode the raw byte544 content, depending on the Content-Encoding used in the response.545 """546 if not hasattr(self, "_decoder"):547 decoders = [] # type: typing.List[Decoder]548 values = self.headers.getlist("content-encoding", split_commas=True)549 for value in values:550 value = value.strip().lower()551 decoder_cls = SUPPORTED_DECODERS[value]552 decoders.append(decoder_cls())553554 if len(decoders) == 1:555 self._decoder = decoders[0]556 elif len(decoders) > 1:557 self._decoder = MultiDecoder(decoders)558 else:559 self._decoder = IdentityDecoder()560561 return self._decoder562563 async def read(self) -> bytes:564 """565 Read and return the response content.566 """567 if not hasattr(self, "_content"):568 content = b""569 async for part in self.stream():570 content += part571 self._content = content572 return self._content573574 async def stream(self) -> typing.AsyncIterator[bytes]:575 """576 A byte-iterator over the decoded response content.577 This allows us to handle gzip, deflate, and brotli encoded responses.578 """579 if hasattr(self, "_content"):580 yield self._content581 else:582 async for chunk in self.raw():583 yield self.decoder.decode(chunk)584 yield self.decoder.flush()585586 async def raw(self) -> typing.AsyncIterator[bytes]:587 """588 A byte-iterator over the raw response content.589 """590 if hasattr(self, "_raw_content"):591 yield self._raw_content592 else:593 if self.is_stream_consumed:594 raise StreamConsumed()595 if self.is_closed:596 raise ResponseClosed()597598 self.is_stream_consumed = True599 async for part in self._raw_stream:600 yield part601 await self.close()602603 async def close(self) -> None:604 """605 Close the response and release the connection.606 Automatically called if the response body is read to completion.607 """608 if not self.is_closed:609 self.is_closed = True610 if self.on_close is not None:611 await self.on_close()612613 @property614 def is_redirect(self) -> bool:615 return (616 self.status_code617 in (618 codes.moved_permanently,619 codes.found,620 codes.see_other,621 codes.temporary_redirect,622 codes.permanent_redirect,623 )624 and "location" in self.headers625 )626627 def __repr__(self) -> str:628 class_name = self.__class__.__name__629 return f"<{class_name}(status_code={self.status_code})>"