models.py
This file
Path
httpcore/models.py
654 lines · 20.4 KiB · Python
Last changed by
Add `raise_for_status` to `Response`Matus Ferechbefore adoptionfb6d14f
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 (18 HttpError,19 InvalidURL,20 ResponseClosed,21 ResponseNotRead,22 StreamConsumed,23)24from .utils import (25 get_reason_phrase,26 is_known_encoding,27 normalize_header_key,28 normalize_header_value,29)3031URLTypes = typing.Union["URL", str]3233HeaderTypes = typing.Union[34 "Headers",35 typing.Dict[typing.AnyStr, typing.AnyStr],36 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],37]3839ByteOrByteStream = typing.Union[bytes, typing.AsyncIterator[bytes]]404142class URL:43 def __init__(self, url: URLTypes, allow_relative: bool = False) -> None:44 if isinstance(url, rfc3986.uri.URIReference):45 self.components = url46 elif isinstance(url, str):47 self.components = rfc3986.api.uri_reference(url)48 else:49 self.components = url.components5051 # Handle IDNA domain names.52 if self.components.authority:53 idna_authority = self.components.authority.encode("idna").decode("ascii")54 if idna_authority != self.components.authority:55 self.components = self.components.copy_with(authority=idna_authority)5657 # Normalize scheme and domain name.58 self.components = self.components.normalize()5960 # Enforce absolute URLs by default.61 if not allow_relative:62 if not self.scheme:63 raise InvalidURL("No scheme included in URL.")64 if self.scheme not in ("http", "https"):65 raise InvalidURL('URL scheme must be "http" or "https".')66 if not self.host:67 raise InvalidURL("No host included in URL.")6869 @property70 def scheme(self) -> str:71 return self.components.scheme or ""7273 @property74 def authority(self) -> str:75 return self.components.authority or ""7677 @property78 def host(self) -> str:79 return self.components.host or ""8081 @property82 def port(self) -> int:83 port = self.components.port84 if port is None:85 return {"https": 443, "http": 80}[self.scheme]86 return int(port)8788 @property89 def path(self) -> str:90 return self.components.path or "/"9192 @property93 def query(self) -> str:94 return self.components.query or ""9596 @property97 def full_path(self) -> str:98 path = self.path99 if self.query:100 path += "?" + self.query101 return path102103 @property104 def fragment(self) -> str:105 return self.components.fragment or ""106107 @property108 def is_ssl(self) -> bool:109 return self.components.scheme == "https"110111 @property112 def is_absolute_url(self) -> bool:113 """114 Return `True` for absolute URLs such as 'http://example.com/path',115 and `False` for relative URLs such as '/path'.116 """117 # We don't use rfc3986's `is_absolute` because it treats118 # URLs with a fragment portion as not absolute.119 # What we actually care about is if the URL provides120 # a scheme and hostname to which connections should be made.121 return self.components.scheme and self.components.host122123 @property124 def is_relative_url(self) -> bool:125 return not self.is_absolute_url126127 @property128 def origin(self) -> "Origin":129 return Origin(self)130131 def copy_with(self, **kwargs: typing.Any) -> "URL":132 return URL(self.components.copy_with(**kwargs))133134 def resolve_with(self, base_url: URLTypes) -> "URL":135 """136 Return an absolute URL, using base_url as the base.137 """138 # We drop any fragment portion, because RFC 3986 strictly139 # treats URLs with a fragment portion as not being absolute URLs.140 base_url = URL(base_url).copy_with(fragment=None)141 return URL(self.components.resolve_with(base_url.components))142143 def __hash__(self) -> int:144 return hash(str(self))145146 def __eq__(self, other: typing.Any) -> bool:147 return isinstance(other, URL) and str(self) == str(other)148149 def __str__(self) -> str:150 return self.components.unsplit()151152 def __repr__(self) -> str:153 class_name = self.__class__.__name__154 url_str = str(self)155 return f"{class_name}({url_str!r})"156157158class Origin:159 def __init__(self, url: URLTypes) -> None:160 if not isinstance(url, URL):161 url = URL(url)162 self.is_ssl = url.is_ssl163 self.host = url.host164 self.port = url.port165166 def __eq__(self, other: typing.Any) -> bool:167 return (168 isinstance(other, self.__class__)169 and self.is_ssl == other.is_ssl170 and self.host == other.host171 and self.port == other.port172 )173174 def __hash__(self) -> int:175 return hash((self.is_ssl, self.host, self.port))176177178class Headers(typing.MutableMapping[str, str]):179 """180 A case-insensitive multidict.181 """182183 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:184 if headers is None:185 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]186 elif isinstance(headers, Headers):187 self._list = list(headers.raw)188 elif isinstance(headers, dict):189 self._list = [190 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))191 for k, v in headers.items()192 ]193 else:194 self._list = [195 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))196 for k, v in headers197 ]198 self._encoding = encoding199200 @property201 def encoding(self) -> str:202 """203 Header encoding is mandated as ascii, but utf-8 or iso-8859-1 may be204 seen in the wild.205 """206 if self._encoding is None:207 for encoding in ["ascii", "utf-8"]:208 for key, value in self.raw:209 try:210 key.decode(encoding)211 value.decode(encoding)212 except UnicodeDecodeError:213 break214 else:215 # The else block runs if 'break' did not occur, meaning216 # all values fitted the encoding.217 self._encoding = encoding218 break219 else:220 # The ISO-8859-1 encoding covers all 256 code points in a byte,221 # so will never raise decode errors.222 self._encoding = "iso-8859-1"223 return self._encoding224225 @encoding.setter226 def encoding(self, value: str) -> None:227 self._encoding = value228229 @property230 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:231 """232 Returns a list of the raw header items, as byte pairs.233 May be mutated in-place.234 """235 return self._list236237 def keys(self) -> typing.List[str]: # type: ignore238 return [key.decode(self.encoding) for key, value in self._list]239240 def values(self) -> typing.List[str]: # type: ignore241 return [value.decode(self.encoding) for key, value in self._list]242243 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore244 return [245 (key.decode(self.encoding), value.decode(self.encoding))246 for key, value in self._list247 ]248249 def get(self, key: str, default: typing.Any = None) -> typing.Any:250 try:251 return self[key]252 except KeyError:253 return default254255 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:256 """257 Return multiple header values.258 """259 get_header_key = key.lower().encode(self.encoding)260261 values = [262 item_value.decode(self.encoding)263 for item_key, item_value in self._list264 if item_key == get_header_key265 ]266267 if not split_commas:268 return values269270 split_values = []271 for value in values:272 split_values.extend([item.strip() for item in value.split(",")])273 return split_values274275 def __getitem__(self, key: str) -> str:276 """277 Return a single header value.278279 If there are multiple headers with the same key, then we concatenate280 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2281 """282 normalized_key = key.lower().encode(self.encoding)283284 items = []285 for header_key, header_value in self._list:286 if header_key == normalized_key:287 items.append(header_value.decode(self.encoding))288289 if items:290 return ", ".join(items)291292 raise KeyError(key)293294 def __setitem__(self, key: str, value: str) -> None:295 """296 Set the header `key` to `value`, removing any duplicate entries.297 Retains insertion order.298 """299 set_key = key.lower().encode(self.encoding)300 set_value = value.encode(self.encoding)301302 found_indexes = []303 for idx, (item_key, item_value) in enumerate(self._list):304 if item_key == set_key:305 found_indexes.append(idx)306307 for idx in reversed(found_indexes[1:]):308 del self._list[idx]309310 if found_indexes:311 idx = found_indexes[0]312 self._list[idx] = (set_key, set_value)313 else:314 self._list.append((set_key, set_value))315316 def __delitem__(self, key: str) -> None:317 """318 Remove the header `key`.319 """320 del_key = key.lower().encode(self.encoding)321322 pop_indexes = []323 for idx, (item_key, item_value) in enumerate(self._list):324 if item_key == del_key:325 pop_indexes.append(idx)326327 for idx in reversed(pop_indexes):328 del self._list[idx]329330 def __contains__(self, key: typing.Any) -> bool:331 get_header_key = key.lower().encode(self.encoding)332 for header_key, header_value in self._list:333 if header_key == get_header_key:334 return True335 return False336337 def __iter__(self) -> typing.Iterator[typing.Any]:338 return iter(self.keys())339340 def __len__(self) -> int:341 return len(self._list)342343 def __eq__(self, other: typing.Any) -> bool:344 if not isinstance(other, Headers):345 return False346 return sorted(self._list) == sorted(other._list)347348 def __repr__(self) -> str:349 class_name = self.__class__.__name__350351 encoding_str = ""352 if self.encoding != "ascii":353 encoding_str = f", encoding={self.encoding!r}"354355 as_dict = dict(self.items())356 if len(as_dict) == len(self):357 return f"{class_name}({as_dict!r}{encoding_str})"358 as_list = self.items()359 return f"{class_name}({as_list!r}{encoding_str})"360361362class Request:363 def __init__(364 self,365 method: str,366 url: typing.Union[str, URL],367 *,368 headers: HeaderTypes = None,369 content: ByteOrByteStream = b"",370 ):371 self.method = method.upper()372 self.url = URL(url) if isinstance(url, str) else url373 if isinstance(content, bytes):374 self.is_streaming = False375 self.content = content376 else:377 self.is_streaming = True378 self.content_aiter = content379 self.headers = Headers(headers)380381 async def read(self) -> bytes:382 """383 Read and return the response content.384 """385 if not hasattr(self, "content"):386 content = b""387 async for part in self.stream():388 content += part389 self.content = content390 return self.content391392 async def stream(self) -> typing.AsyncIterator[bytes]:393 if self.is_streaming:394 async for part in self.content_aiter:395 yield part396 elif self.content:397 yield self.content398399 def prepare(self) -> None:400 """401 Adds in any default headers. When using the `Client`, this will402 end up being called into by the `prepare_request()` stage.403404 You can omit this behavior by calling `Client.send()` with an405 explicitly built `Request` instance.406 """407 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]408409 has_host = "host" in self.headers410 has_content_length = (411 "content-length" in self.headers or "transfer-encoding" in self.headers412 )413 has_accept_encoding = "accept-encoding" in self.headers414415 if not has_host and self.url.authority:416 auto_headers.append((b"host", self.url.authority.encode("ascii")))417 if not has_content_length:418 if self.is_streaming:419 auto_headers.append((b"transfer-encoding", b"chunked"))420 elif self.content:421 content_length = str(len(self.content)).encode()422 auto_headers.append((b"content-length", content_length))423 if not has_accept_encoding:424 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))425426 for item in reversed(auto_headers):427 self.headers.raw.insert(0, item)428429 def __repr__(self) -> str:430 class_name = self.__class__.__name__431 url = str(self.url)432 return f"<{class_name}({self.method}, {url})>"433434435class Response:436 def __init__(437 self,438 status_code: int,439 *,440 reason_phrase: str = None,441 protocol: str = None,442 headers: HeaderTypes = None,443 content: ByteOrByteStream = b"",444 on_close: typing.Callable = None,445 request: Request = None,446 history: typing.List["Response"] = None,447 ):448 try:449 # Use a StatusCode IntEnum if possible, for a nicer representation.450 self.status_code = codes(status_code) # type: int451 except ValueError:452 self.status_code = status_code453 self.reason_phrase = reason_phrase or get_reason_phrase(status_code)454 self.protocol = protocol455 self.headers = Headers(headers)456457 if isinstance(content, bytes):458 self.is_closed = True459 self.is_stream_consumed = True460 self._raw_content = content461 else:462 self.is_closed = False463 self.is_stream_consumed = False464 self._raw_stream = content465466 self.on_close = on_close467 self.request = request468 self.history = [] if history is None else list(history)469 self.next = None # typing.Optional[typing.Callable]470471 @property472 def url(self) -> typing.Optional[URL]:473 """474 Returns the URL for which the request was made.475476 Requires that `request` was provided when instantiating the response.477 """478 return None if self.request is None else self.request.url479480 @property481 def content(self) -> bytes:482 if not hasattr(self, "_content"):483 if hasattr(self, "_raw_content"):484 content = self.decoder.decode(self._raw_content)485 content += self.decoder.flush()486 self._content = content487 else:488 raise ResponseNotRead()489 return self._content490491 @property492 def text(self) -> str:493 if not hasattr(self, "_text"):494 content = self.content495 if not content:496 self._text = ""497 else:498 encoding = self.encoding499 self._text = content.decode(encoding, errors="replace")500 return self._text501502 @property503 def encoding(self) -> str:504 if not hasattr(self, "_encoding"):505 encoding = self.charset_encoding506 if encoding is None or not is_known_encoding(encoding):507 encoding = self.apparent_encoding508 if encoding is None or not is_known_encoding(encoding):509 encoding = "utf-8"510 self._encoding = encoding511 return self._encoding512513 @encoding.setter514 def encoding(self, value: str) -> None:515 self._encoding = value516517 @property518 def charset_encoding(self) -> typing.Optional[str]:519 """520 Return the encoding, as specified by the Content-Type header.521 """522 content_type = self.headers.get("Content-Type")523 if content_type is None:524 return None525526 parsed = cgi.parse_header(content_type)527 media_type, params = parsed[0], parsed[-1]528 if "charset" in params:529 return params["charset"].strip("'\"")530531 # RFC 2616 specifies that 'iso-8859-1' should be used as the default532 # for 'text/*' media types, if no charset is provided.533 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1534 if media_type.startswith("text/"):535 return "iso-8859-1"536537 return None538539 @property540 def apparent_encoding(self) -> typing.Optional[str]:541 """542 Return the encoding, as it appears to autodetection.543 """544 return chardet.detect(self.content)["encoding"]545546 @property547 def decoder(self) -> Decoder:548 """549 Returns a decoder instance which can be used to decode the raw byte550 content, depending on the Content-Encoding used in the response.551 """552 if not hasattr(self, "_decoder"):553 decoders = [] # type: typing.List[Decoder]554 values = self.headers.getlist("content-encoding", split_commas=True)555 for value in values:556 value = value.strip().lower()557 decoder_cls = SUPPORTED_DECODERS[value]558 decoders.append(decoder_cls())559560 if len(decoders) == 1:561 self._decoder = decoders[0]562 elif len(decoders) > 1:563 self._decoder = MultiDecoder(decoders)564 else:565 self._decoder = IdentityDecoder()566567 return self._decoder568569 async def read(self) -> bytes:570 """571 Read and return the response content.572 """573 if not hasattr(self, "_content"):574 content = b""575 async for part in self.stream():576 content += part577 self._content = content578 return self._content579580 async def stream(self) -> typing.AsyncIterator[bytes]:581 """582 A byte-iterator over the decoded response content.583 This allows us to handle gzip, deflate, and brotli encoded responses.584 """585 if hasattr(self, "_content"):586 yield self._content587 else:588 async for chunk in self.raw():589 yield self.decoder.decode(chunk)590 yield self.decoder.flush()591592 async def raw(self) -> typing.AsyncIterator[bytes]:593 """594 A byte-iterator over the raw response content.595 """596 if hasattr(self, "_raw_content"):597 yield self._raw_content598 else:599 if self.is_stream_consumed:600 raise StreamConsumed()601 if self.is_closed:602 raise ResponseClosed()603604 self.is_stream_consumed = True605 async for part in self._raw_stream:606 yield part607 await self.close()608609 async def close(self) -> None:610 """611 Close the response and release the connection.612 Automatically called if the response body is read to completion.613 """614 if not self.is_closed:615 self.is_closed = True616 if self.on_close is not None:617 await self.on_close()618619 @property620 def is_redirect(self) -> bool:621 return (622 self.status_code623 in (624 codes.moved_permanently,625 codes.found,626 codes.see_other,627 codes.temporary_redirect,628 codes.permanent_redirect,629 )630 and "location" in self.headers631 )632633 def __repr__(self) -> str:634 class_name = self.__class__.__name__635 return f"<{class_name}(status_code={self.status_code})>"636637 def raise_for_status(self) -> None:638 """639 Raise the `HttpError` if one occurred.640 """641 message = (642 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"643 "For more information check: https://httpstatuses.com/{0.status_code}"644 )645646 if 400 <= self.status_code < 500:647 message = message.format(self, error_type="Client Error")648 elif 500 <= self.status_code < 600:649 message = message.format(self, error_type="Server Error")650 else:651 message = ""652653 if message:654 raise HttpError(message)