models.py
This file
Path
httpcore/models.py
630 lines · 19.8 KiB · Python
Last changed by
Still truckin' onTom Christiebefore adoption6cb5c0d
History of this fileTake it
1import cgi2import typing34import chardet5import idna6import rfc398678from .config import SSLConfig, TimeoutConfig9from .decoders import (10 ACCEPT_ENCODING,11 SUPPORTED_DECODERS,12 Decoder,13 IdentityDecoder,14 MultiDecoder,15)16from .exceptions import InvalidURL, ResponseClosed, ResponseNotRead, StreamConsumed17from .status_codes import codes18from .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 schema 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 # but we want to treat them as such for the purposes of135 base_url = URL(base_url).copy_with(fragment=None)136 return URL(self.components.resolve_with(base_url.components))137138 def __hash__(self) -> int:139 return hash(str(self))140141 def __eq__(self, other: typing.Any) -> bool:142 return isinstance(other, URL) and str(self) == str(other)143144 def __str__(self) -> str:145 return self.components.unsplit()146147 def __repr__(self) -> str:148 class_name = self.__class__.__name__149 url_str = str(self)150 return f"{class_name}({url_str!r})"151152153class Origin:154 def __init__(self, url: URLTypes) -> None:155 if not isinstance(url, URL):156 url = URL(url)157 self.is_ssl = url.is_ssl158 self.host = url.host159 self.port = url.port160161 def __eq__(self, other: typing.Any) -> bool:162 return (163 isinstance(other, self.__class__)164 and self.is_ssl == other.is_ssl165 and self.host == other.host166 and self.port == other.port167 )168169 def __hash__(self) -> int:170 return hash((self.is_ssl, self.host, self.port))171172173class Headers(typing.MutableMapping[str, str]):174 """175 A case-insensitive multidict.176 """177178 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:179 if headers is None:180 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]181 elif isinstance(headers, Headers):182 self._list = list(headers.raw)183 elif isinstance(headers, dict):184 self._list = [185 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))186 for k, v in headers.items()187 ]188 else:189 self._list = [190 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))191 for k, v in headers192 ]193 self._encoding = encoding194195 @property196 def encoding(self) -> str:197 """198 Header encoding is mandated as ascii, but utf-8 or iso-8859-1 may be199 seen in the wild.200 """201 if self._encoding is None:202 for encoding in ["ascii", "utf-8"]:203 for key, value in self.raw:204 try:205 key.decode(encoding)206 value.decode(encoding)207 except UnicodeDecodeError:208 break209 else:210 # The else block runs if 'break' did not occur, meaning211 # all values fitted the encoding.212 self._encoding = encoding213 break214 else:215 # The ISO-8859-1 encoding covers all 256 code points in a byte,216 # so will never raise decode errors.217 self._encoding = "iso-8859-1"218 return self._encoding219220 @encoding.setter221 def encoding(self, value: str) -> None:222 self._encoding = value223224 @property225 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:226 """227 Returns a list of the raw header items, as byte pairs.228 May be mutated in-place.229 """230 return self._list231232 def keys(self) -> typing.List[str]: # type: ignore233 return [key.decode(self.encoding) for key, value in self._list]234235 def values(self) -> typing.List[str]: # type: ignore236 return [value.decode(self.encoding) for key, value in self._list]237238 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore239 return [240 (key.decode(self.encoding), value.decode(self.encoding))241 for key, value in self._list242 ]243244 def get(self, key: str, default: typing.Any = None) -> typing.Any:245 try:246 return self[key]247 except KeyError:248 return default249250 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:251 """252 Return multiple header values.253 """254 get_header_key = key.lower().encode(self.encoding)255256 values = [257 item_value.decode(self.encoding)258 for item_key, item_value in self._list259 if item_key == get_header_key260 ]261262 if not split_commas:263 return values264265 split_values = []266 for value in values:267 split_values.extend([item.strip() for item in value.split(",")])268 return split_values269270 def __getitem__(self, key: str) -> str:271 """272 Return a single header value.273274 If there are multiple headers with the same key, then we concatenate275 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2276 """277 normalized_key = key.lower().encode(self.encoding)278279 items = []280 for header_key, header_value in self._list:281 if header_key == normalized_key:282 items.append(header_value.decode(self.encoding))283284 if items:285 return ", ".join(items)286287 raise KeyError(key)288289 def __setitem__(self, key: str, value: str) -> None:290 """291 Set the header `key` to `value`, removing any duplicate entries.292 Retains insertion order.293 """294 set_key = key.lower().encode(self.encoding)295 set_value = value.encode(self.encoding)296297 found_indexes = []298 for idx, (item_key, item_value) in enumerate(self._list):299 if item_key == set_key:300 found_indexes.append(idx)301302 for idx in reversed(found_indexes[1:]):303 del self._list[idx]304305 if found_indexes:306 idx = found_indexes[0]307 self._list[idx] = (set_key, set_value)308 else:309 self._list.append((set_key, set_value))310311 def __delitem__(self, key: str) -> None:312 """313 Remove the header `key`.314 """315 del_key = key.lower().encode(self.encoding)316317 pop_indexes = []318 for idx, (item_key, item_value) in enumerate(self._list):319 if item_key == del_key:320 pop_indexes.append(idx)321322 for idx in reversed(pop_indexes):323 del self._list[idx]324325 def __contains__(self, key: typing.Any) -> bool:326 get_header_key = key.lower().encode(self.encoding)327 for header_key, header_value in self._list:328 if header_key == get_header_key:329 return True330 return False331332 def __iter__(self) -> typing.Iterator[typing.Any]:333 return iter(self.keys())334335 def __len__(self) -> int:336 return len(self._list)337338 def __eq__(self, other: typing.Any) -> bool:339 if not isinstance(other, Headers):340 return False341 return sorted(self._list) == sorted(other._list)342343 def __repr__(self) -> str:344 class_name = self.__class__.__name__345346 encoding_str = ""347 if self.encoding != "ascii":348 encoding_str = f", encoding={self.encoding!r}"349350 as_dict = dict(self.items())351 if len(as_dict) == len(self):352 return f"{class_name}({as_dict!r}{encoding_str})"353 as_list = self.items()354 return f"{class_name}({as_list!r}{encoding_str})"355356357class Request:358 def __init__(359 self,360 method: str,361 url: typing.Union[str, URL],362 *,363 headers: HeaderTypes = None,364 content: ByteOrByteStream = b"",365 ):366 self.method = method.upper()367 self.url = URL(url) if isinstance(url, str) else url368 if isinstance(content, bytes):369 self.is_streaming = False370 self.content = content371 else:372 self.is_streaming = True373 self.content_aiter = content374 self.headers = Headers(headers)375376 async def read(self) -> bytes:377 """378 Read and return the response content.379 """380 if not hasattr(self, "content"):381 content = b""382 async for part in self.stream():383 content += part384 self.content = content385 return self.content386387 async def stream(self) -> typing.AsyncIterator[bytes]:388 if self.is_streaming:389 async for part in self.content_aiter:390 yield part391 elif self.content:392 yield self.content393394 def prepare(self) -> None:395 """396 Adds in any default headers. When using the `Client`, this will397 end up being called into by the `prepare_request()` stage.398399 You can omit this behavior by calling `Client.send()` with an400 explicitly built `Request` instance.401 """402 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]403404 has_host = "host" in self.headers405 has_content_length = (406 "content-length" in self.headers or "transfer-encoding" in self.headers407 )408 has_accept_encoding = "accept-encoding" in self.headers409410 if not has_host and self.url.authority:411 auto_headers.append((b"host", self.url.authority.encode("ascii")))412 if not has_content_length:413 if self.is_streaming:414 auto_headers.append((b"transfer-encoding", b"chunked"))415 elif self.content:416 content_length = str(len(self.content)).encode()417 auto_headers.append((b"content-length", content_length))418 if not has_accept_encoding:419 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))420421 for item in reversed(auto_headers):422 self.headers.raw.insert(0, item)423424 def __repr__(self) -> str:425 class_name = self.__class__.__name__426 url = str(self.url)427 return f"<{class_name}({self.method}, {url})>"428429430class Response:431 def __init__(432 self,433 status_code: int,434 *,435 reason_phrase: str = None,436 protocol: str = None,437 headers: HeaderTypes = None,438 content: ByteOrByteStream = b"",439 on_close: typing.Callable = None,440 request: Request = None,441 history: typing.List["Response"] = None,442 ):443 try:444 # Use a StatusCode IntEnum if possible, for a nicer representation.445 self.status_code = codes(status_code) # type: int446 except ValueError:447 self.status_code = status_code448 self.reason_phrase = reason_phrase or get_reason_phrase(status_code)449 self.protocol = protocol450 self.headers = Headers(headers)451452 if isinstance(content, bytes):453 self.is_closed = True454 self.is_stream_consumed = True455 self._raw_content = content456 else:457 self.is_closed = False458 self.is_stream_consumed = False459 self._raw_stream = content460461 self.on_close = on_close462 self.request = request463 self.history = [] if history is None else list(history)464 self.next = None # typing.Optional[typing.Callable]465466 @property467 def url(self) -> typing.Optional[URL]:468 """469 Returns the URL for which the request was made.470471 Requires that `request` was provided when instantiating the response.472 """473 return None if self.request is None else self.request.url474475 @property476 def content(self) -> bytes:477 if not hasattr(self, "_content"):478 if hasattr(self, "_raw_content"):479 content = self.decoder.decode(self._raw_content)480 content += self.decoder.flush()481 self._content = content482 else:483 raise ResponseNotRead()484 return self._content485486 @property487 def text(self) -> str:488 if not hasattr(self, "_text"):489 content = self.content490 if not content:491 self._text = ""492 else:493 encoding = self.encoding494 self._text = content.decode(encoding, errors="replace")495 return self._text496497 @property498 def encoding(self) -> str:499 if not hasattr(self, "_encoding"):500 encoding = self.charset_encoding501 if encoding is None or not is_known_encoding(encoding):502 encoding = self.apparent_encoding503 if encoding is None or not is_known_encoding(encoding):504 encoding = "utf-8"505 self._encoding = encoding506 return self._encoding507508 @encoding.setter509 def encoding(self, value: str) -> None:510 self._encoding = value511512 @property513 def charset_encoding(self) -> typing.Optional[str]:514 """515 Return the encoding, as specified by the Content-Type header.516 """517 content_type = self.headers.get("Content-Type")518 if content_type is None:519 return None520521 parsed = cgi.parse_header(content_type)522 media_type, params = parsed[0], parsed[-1]523 if "charset" in params:524 return params["charset"].strip("'\"")525526 # RFC 2616 specifies that 'iso-8859-1' should be used as the default527 # for 'text/*' media types, if no charset is provided.528 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1529 if media_type.startswith("text/"):530 return "iso-8859-1"531532 return None533534 @property535 def apparent_encoding(self) -> typing.Optional[str]:536 """537 Return the encoding, as it appears to autodetection.538 """539 return chardet.detect(self.content)["encoding"]540541 @property542 def decoder(self) -> Decoder:543 """544 Returns a decoder instance which can be used to decode the raw byte545 content, depending on the Content-Encoding used in the response.546 """547 if not hasattr(self, "_decoder"):548 decoders = [] # type: typing.List[Decoder]549 values = self.headers.getlist("content-encoding", split_commas=True)550 for value in values:551 value = value.strip().lower()552 decoder_cls = SUPPORTED_DECODERS[value]553 decoders.append(decoder_cls())554555 if len(decoders) == 1:556 self._decoder = decoders[0]557 elif len(decoders) > 1:558 self._decoder = MultiDecoder(decoders)559 else:560 self._decoder = IdentityDecoder()561562 return self._decoder563564 async def read(self) -> bytes:565 """566 Read and return the response content.567 """568 if not hasattr(self, "_content"):569 content = b""570 async for part in self.stream():571 content += part572 self._content = content573 return self._content574575 async def stream(self) -> typing.AsyncIterator[bytes]:576 """577 A byte-iterator over the decoded response content.578 This allows us to handle gzip, deflate, and brotli encoded responses.579 """580 if hasattr(self, "_content"):581 yield self._content582 else:583 async for chunk in self.raw():584 yield self.decoder.decode(chunk)585 yield self.decoder.flush()586587 async def raw(self) -> typing.AsyncIterator[bytes]:588 """589 A byte-iterator over the raw response content.590 """591 if hasattr(self, "_raw_content"):592 yield self._raw_content593 else:594 if self.is_stream_consumed:595 raise StreamConsumed()596 if self.is_closed:597 raise ResponseClosed()598599 self.is_stream_consumed = True600 async for part in self._raw_stream:601 yield part602 await self.close()603604 async def close(self) -> None:605 """606 Close the response and release the connection.607 Automatically called if the response body is read to completion.608 """609 if not self.is_closed:610 self.is_closed = True611 if self.on_close is not None:612 await self.on_close()613614 @property615 def is_redirect(self) -> bool:616 return (617 self.status_code618 in (619 codes.moved_permanently,620 codes.found,621 codes.see_other,622 codes.temporary_redirect,623 codes.permanent_redirect,624 )625 and "location" in self.headers626 )627628 def __repr__(self) -> str:629 class_name = self.__class__.__name__630 return f"<{class_name}(status_code={self.status_code})>"