models.py
This file
Path
httpcore/models.py
753 lines · 23.4 KiB · Python
Last changed by
Support url-encoded data in requestsTom Christiebefore adoptione91c69d
History of this fileTake it
1import cgi2import typing3from urllib.parse import parse_qsl, urlencode45import chardet6import idna7import rfc398689from .config import SSLConfig, TimeoutConfig10from .constants import codes11from .decoders import (12 ACCEPT_ENCODING,13 SUPPORTED_DECODERS,14 Decoder,15 IdentityDecoder,16 MultiDecoder,17)18from .exceptions import (19 HttpError,20 InvalidURL,21 ResponseClosed,22 ResponseNotRead,23 StreamConsumed,24)25from .utils import (26 get_reason_phrase,27 is_known_encoding,28 normalize_header_key,29 normalize_header_value,30)3132URLTypes = typing.Union["URL", str]3334QueryParamTypes = typing.Union[35 "QueryParams",36 typing.Mapping[str, str],37 typing.List[typing.Tuple[typing.Any, typing.Any]],38 str,39]4041HeaderTypes = typing.Union[42 "Headers",43 typing.Dict[typing.AnyStr, typing.AnyStr],44 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],45]4647RequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]4849ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]505152class URL:53 def __init__(54 self,55 url: URLTypes,56 allow_relative: bool = False,57 query_params: QueryParamTypes = None,58 ) -> None:59 if isinstance(url, rfc3986.uri.URIReference):60 self.components = url61 elif isinstance(url, str):62 self.components = rfc3986.api.uri_reference(url)63 else:64 self.components = url.components6566 # Handle IDNA domain names.67 if self.components.authority:68 idna_authority = self.components.authority.encode("idna").decode("ascii")69 if idna_authority != self.components.authority:70 self.components = self.components.copy_with(authority=idna_authority)7172 # Normalize scheme and domain name.73 self.components = self.components.normalize()7475 # Add any query parameters.76 if query_params:77 query_string = str(QueryParams(query_params))78 self.components = self.components.copy_with(query=query_string)7980 # Enforce absolute URLs by default.81 if not allow_relative:82 if not self.scheme:83 raise InvalidURL("No scheme included in URL.")84 if self.scheme not in ("http", "https"):85 raise InvalidURL('URL scheme must be "http" or "https".')86 if not self.host:87 raise InvalidURL("No host included in URL.")8889 @property90 def scheme(self) -> str:91 return self.components.scheme or ""9293 @property94 def authority(self) -> str:95 return self.components.authority or ""9697 @property98 def host(self) -> str:99 return self.components.host or ""100101 @property102 def port(self) -> int:103 port = self.components.port104 if port is None:105 return {"https": 443, "http": 80}[self.scheme]106 return int(port)107108 @property109 def path(self) -> str:110 return self.components.path or "/"111112 @property113 def query(self) -> str:114 return self.components.query or ""115116 @property117 def full_path(self) -> str:118 path = self.path119 if self.query:120 path += "?" + self.query121 return path122123 @property124 def fragment(self) -> str:125 return self.components.fragment or ""126127 @property128 def is_ssl(self) -> bool:129 return self.components.scheme == "https"130131 @property132 def is_absolute_url(self) -> bool:133 """134 Return `True` for absolute URLs such as 'http://example.com/path',135 and `False` for relative URLs such as '/path'.136 """137 # We don't use rfc3986's `is_absolute` because it treats138 # URLs with a fragment portion as not absolute.139 # What we actually care about is if the URL provides140 # a scheme and hostname to which connections should be made.141 return self.components.scheme and self.components.host142143 @property144 def is_relative_url(self) -> bool:145 return not self.is_absolute_url146147 @property148 def origin(self) -> "Origin":149 return Origin(self)150151 def copy_with(self, **kwargs: typing.Any) -> "URL":152 return URL(self.components.copy_with(**kwargs))153154 def resolve_with(self, base_url: URLTypes) -> "URL":155 """156 Return an absolute URL, using base_url as the base.157 """158 # We drop any fragment portion, because RFC 3986 strictly159 # treats URLs with a fragment portion as not being absolute URLs.160 base_url = URL(base_url).copy_with(fragment=None)161 return URL(self.components.resolve_with(base_url.components))162163 def __hash__(self) -> int:164 return hash(str(self))165166 def __eq__(self, other: typing.Any) -> bool:167 return isinstance(other, URL) and str(self) == str(other)168169 def __str__(self) -> str:170 return self.components.unsplit()171172 def __repr__(self) -> str:173 class_name = self.__class__.__name__174 url_str = str(self)175 return f"{class_name}({url_str!r})"176177178class Origin:179 """180 The URL scheme and authority information, as a comparable, hashable object.181 """182183 def __init__(self, url: URLTypes) -> None:184 if not isinstance(url, URL):185 url = URL(url)186 self.is_ssl = url.is_ssl187 self.host = url.host188 self.port = url.port189190 def __eq__(self, other: typing.Any) -> bool:191 return (192 isinstance(other, self.__class__)193 and self.is_ssl == other.is_ssl194 and self.host == other.host195 and self.port == other.port196 )197198 def __hash__(self) -> int:199 return hash((self.is_ssl, self.host, self.port))200201202class QueryParams(typing.Mapping[str, str]):203 """204 URL query parameters, as a multi-dict.205 """206207 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:208 assert len(args) < 2, "Too many arguments."209 assert not (args and kwargs), "Cannot mix named and unnamed arguments."210211 value = args[0] if args else kwargs212213 if isinstance(value, str):214 items = parse_qsl(value)215 elif isinstance(value, QueryParams):216 items = value.multi_items()217 elif isinstance(value, list):218 items = value219 else:220 items = value.items() # type: ignore221222 self._list = [(str(k), str(v)) for k, v in items]223 self._dict = {str(k): str(v) for k, v in items}224225 def getlist(self, key: typing.Any) -> typing.List[str]:226 return [item_value for item_key, item_value in self._list if item_key == key]227228 def keys(self) -> typing.KeysView:229 return self._dict.keys()230231 def values(self) -> typing.ValuesView:232 return self._dict.values()233234 def items(self) -> typing.ItemsView:235 return self._dict.items()236237 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:238 return list(self._list)239240 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:241 if key in self._dict:242 return self._dict[key]243 return default244245 def __getitem__(self, key: typing.Any) -> str:246 return self._dict[key]247248 def __contains__(self, key: typing.Any) -> bool:249 return key in self._dict250251 def __iter__(self) -> typing.Iterator[typing.Any]:252 return iter(self.keys())253254 def __len__(self) -> int:255 return len(self._dict)256257 def __eq__(self, other: typing.Any) -> bool:258 if not isinstance(other, self.__class__):259 return False260 return sorted(self._list) == sorted(other._list)261262 def __str__(self) -> str:263 return urlencode(self._list)264265 def __repr__(self) -> str:266 class_name = self.__class__.__name__267 query_string = str(self)268 return f"{class_name}({query_string!r})"269270271class Headers(typing.MutableMapping[str, str]):272 """273 HTTP headers, as a case-insensitive multi-dict.274 """275276 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:277 if headers is None:278 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]279 elif isinstance(headers, Headers):280 self._list = list(headers.raw)281 elif isinstance(headers, dict):282 self._list = [283 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))284 for k, v in headers.items()285 ]286 else:287 self._list = [288 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))289 for k, v in headers290 ]291 self._encoding = encoding292293 @property294 def encoding(self) -> str:295 """296 Header encoding is mandated as ascii, but we allow fallbacks to utf-8297 or iso-8859-1.298 """299 if self._encoding is None:300 for encoding in ["ascii", "utf-8"]:301 for key, value in self.raw:302 try:303 key.decode(encoding)304 value.decode(encoding)305 except UnicodeDecodeError:306 break307 else:308 # The else block runs if 'break' did not occur, meaning309 # all values fitted the encoding.310 self._encoding = encoding311 break312 else:313 # The ISO-8859-1 encoding covers all 256 code points in a byte,314 # so will never raise decode errors.315 self._encoding = "iso-8859-1"316 return self._encoding317318 @encoding.setter319 def encoding(self, value: str) -> None:320 self._encoding = value321322 @property323 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:324 """325 Returns a list of the raw header items, as byte pairs.326 May be mutated in-place.327 """328 return self._list329330 def keys(self) -> typing.List[str]: # type: ignore331 return [key.decode(self.encoding) for key, value in self._list]332333 def values(self) -> typing.List[str]: # type: ignore334 return [value.decode(self.encoding) for key, value in self._list]335336 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore337 return [338 (key.decode(self.encoding), value.decode(self.encoding))339 for key, value in self._list340 ]341342 def get(self, key: str, default: typing.Any = None) -> typing.Any:343 try:344 return self[key]345 except KeyError:346 return default347348 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:349 """350 Return multiple header values.351 """352 get_header_key = key.lower().encode(self.encoding)353354 values = [355 item_value.decode(self.encoding)356 for item_key, item_value in self._list357 if item_key == get_header_key358 ]359360 if not split_commas:361 return values362363 split_values = []364 for value in values:365 split_values.extend([item.strip() for item in value.split(",")])366 return split_values367368 def __getitem__(self, key: str) -> str:369 """370 Return a single header value.371372 If there are multiple headers with the same key, then we concatenate373 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2374 """375 normalized_key = key.lower().encode(self.encoding)376377 items = []378 for header_key, header_value in self._list:379 if header_key == normalized_key:380 items.append(header_value.decode(self.encoding))381382 if items:383 return ", ".join(items)384385 raise KeyError(key)386387 def __setitem__(self, key: str, value: str) -> None:388 """389 Set the header `key` to `value`, removing any duplicate entries.390 Retains insertion order.391 """392 set_key = key.lower().encode(self.encoding)393 set_value = value.encode(self.encoding)394395 found_indexes = []396 for idx, (item_key, item_value) in enumerate(self._list):397 if item_key == set_key:398 found_indexes.append(idx)399400 for idx in reversed(found_indexes[1:]):401 del self._list[idx]402403 if found_indexes:404 idx = found_indexes[0]405 self._list[idx] = (set_key, set_value)406 else:407 self._list.append((set_key, set_value))408409 def __delitem__(self, key: str) -> None:410 """411 Remove the header `key`.412 """413 del_key = key.lower().encode(self.encoding)414415 pop_indexes = []416 for idx, (item_key, item_value) in enumerate(self._list):417 if item_key == del_key:418 pop_indexes.append(idx)419420 for idx in reversed(pop_indexes):421 del self._list[idx]422423 def __contains__(self, key: typing.Any) -> bool:424 get_header_key = key.lower().encode(self.encoding)425 for header_key, header_value in self._list:426 if header_key == get_header_key:427 return True428 return False429430 def __iter__(self) -> typing.Iterator[typing.Any]:431 return iter(self.keys())432433 def __len__(self) -> int:434 return len(self._list)435436 def __eq__(self, other: typing.Any) -> bool:437 if not isinstance(other, Headers):438 return False439 return sorted(self._list) == sorted(other._list)440441 def __repr__(self) -> str:442 class_name = self.__class__.__name__443444 encoding_str = ""445 if self.encoding != "ascii":446 encoding_str = f", encoding={self.encoding!r}"447448 as_dict = dict(self.items())449 if len(as_dict) == len(self):450 return f"{class_name}({as_dict!r}{encoding_str})"451 as_list = self.items()452 return f"{class_name}({as_list!r}{encoding_str})"453454455class Request:456 def __init__(457 self,458 method: str,459 url: typing.Union[str, URL],460 *,461 data: RequestData = b"",462 query_params: QueryParamTypes = None,463 headers: HeaderTypes = None,464 ):465 self.method = method.upper()466 self.url = URL(url, query_params=query_params)467 self.headers = Headers(headers)468469 if isinstance(data, bytes):470 self.is_streaming = False471 self.content = data472 elif isinstance(data, dict):473 self.is_streaming = False474 self.content = urlencode(data, doseq=True).encode("utf-8")475 self.headers["Content-Type"] = "application/x-www-form-urlencoded"476 else:477 self.is_streaming = True478 self.content_aiter = data479480 async def read(self) -> bytes:481 """482 Read and return the response content.483 """484 if not hasattr(self, "content"):485 content = b""486 async for part in self.stream():487 content += part488 self.content = content489 return self.content490491 async def stream(self) -> typing.AsyncIterator[bytes]:492 if self.is_streaming:493 async for part in self.content_aiter:494 yield part495 elif self.content:496 yield self.content497498 def prepare(self) -> None:499 """500 Adds in any default headers. When using the `Client`, this will501 end up being called into by the `prepare_request()` stage.502503 You can omit this behavior by calling `Client.send()` with an504 explicitly built `Request` instance.505 """506 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]507508 has_host = "host" in self.headers509 has_content_length = (510 "content-length" in self.headers or "transfer-encoding" in self.headers511 )512 has_accept_encoding = "accept-encoding" in self.headers513514 if not has_host and self.url.authority:515 auto_headers.append((b"host", self.url.authority.encode("ascii")))516 if not has_content_length:517 if self.is_streaming:518 auto_headers.append((b"transfer-encoding", b"chunked"))519 elif self.content:520 content_length = str(len(self.content)).encode()521 auto_headers.append((b"content-length", content_length))522 if not has_accept_encoding:523 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))524525 for item in reversed(auto_headers):526 self.headers.raw.insert(0, item)527528 def __repr__(self) -> str:529 class_name = self.__class__.__name__530 url = str(self.url)531 return f"<{class_name}({self.method!r}, {url!r})>"532533534class Response:535 def __init__(536 self,537 status_code: int,538 *,539 reason_phrase: str = None,540 protocol: str = None,541 headers: HeaderTypes = None,542 content: ResponseContent = b"",543 on_close: typing.Callable = None,544 request: Request = None,545 history: typing.List["Response"] = None,546 ):547 try:548 # Use a StatusCode IntEnum if possible, for a nicer representation.549 self.status_code = codes(status_code) # type: int550 except ValueError:551 self.status_code = status_code552 self.reason_phrase = reason_phrase or get_reason_phrase(status_code)553 self.protocol = protocol554 self.headers = Headers(headers)555556 if isinstance(content, bytes):557 self.is_closed = True558 self.is_stream_consumed = True559 self._raw_content = content560 else:561 self.is_closed = False562 self.is_stream_consumed = False563 self._raw_stream = content564565 self.on_close = on_close566 self.request = request567 self.history = [] if history is None else list(history)568 self.next = None # typing.Optional[typing.Callable]569570 @property571 def url(self) -> typing.Optional[URL]:572 """573 Returns the URL for which the request was made.574575 Requires that `request` was provided when instantiating the response.576 """577 return None if self.request is None else self.request.url578579 @property580 def content(self) -> bytes:581 if not hasattr(self, "_content"):582 if hasattr(self, "_raw_content"):583 content = self.decoder.decode(self._raw_content)584 content += self.decoder.flush()585 self._content = content586 else:587 raise ResponseNotRead()588 return self._content589590 @property591 def text(self) -> str:592 if not hasattr(self, "_text"):593 content = self.content594 if not content:595 self._text = ""596 else:597 encoding = self.encoding598 self._text = content.decode(encoding, errors="replace")599 return self._text600601 @property602 def encoding(self) -> str:603 if not hasattr(self, "_encoding"):604 encoding = self.charset_encoding605 if encoding is None or not is_known_encoding(encoding):606 encoding = self.apparent_encoding607 if encoding is None or not is_known_encoding(encoding):608 encoding = "utf-8"609 self._encoding = encoding610 return self._encoding611612 @encoding.setter613 def encoding(self, value: str) -> None:614 self._encoding = value615616 @property617 def charset_encoding(self) -> typing.Optional[str]:618 """619 Return the encoding, as specified by the Content-Type header.620 """621 content_type = self.headers.get("Content-Type")622 if content_type is None:623 return None624625 parsed = cgi.parse_header(content_type)626 media_type, params = parsed[0], parsed[-1]627 if "charset" in params:628 return params["charset"].strip("'\"")629630 # RFC 2616 specifies that 'iso-8859-1' should be used as the default631 # for 'text/*' media types, if no charset is provided.632 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1633 if media_type.startswith("text/"):634 return "iso-8859-1"635636 return None637638 @property639 def apparent_encoding(self) -> typing.Optional[str]:640 """641 Return the encoding, as it appears to autodetection.642 """643 return chardet.detect(self.content)["encoding"]644645 @property646 def decoder(self) -> Decoder:647 """648 Returns a decoder instance which can be used to decode the raw byte649 content, depending on the Content-Encoding used in the response.650 """651 if not hasattr(self, "_decoder"):652 decoders = [] # type: typing.List[Decoder]653 values = self.headers.getlist("content-encoding", split_commas=True)654 for value in values:655 value = value.strip().lower()656 decoder_cls = SUPPORTED_DECODERS[value]657 decoders.append(decoder_cls())658659 if len(decoders) == 1:660 self._decoder = decoders[0]661 elif len(decoders) > 1:662 self._decoder = MultiDecoder(decoders)663 else:664 self._decoder = IdentityDecoder()665666 return self._decoder667668 async def read(self) -> bytes:669 """670 Read and return the response content.671 """672 if not hasattr(self, "_content"):673 content = b""674 async for part in self.stream():675 content += part676 self._content = content677 return self._content678679 async def stream(self) -> typing.AsyncIterator[bytes]:680 """681 A byte-iterator over the decoded response content.682 This allows us to handle gzip, deflate, and brotli encoded responses.683 """684 if hasattr(self, "_content"):685 yield self._content686 else:687 async for chunk in self.raw():688 yield self.decoder.decode(chunk)689 yield self.decoder.flush()690691 async def raw(self) -> typing.AsyncIterator[bytes]:692 """693 A byte-iterator over the raw response content.694 """695 if hasattr(self, "_raw_content"):696 yield self._raw_content697 else:698 if self.is_stream_consumed:699 raise StreamConsumed()700 if self.is_closed:701 raise ResponseClosed()702703 self.is_stream_consumed = True704 async for part in self._raw_stream:705 yield part706 await self.close()707708 async def close(self) -> None:709 """710 Close the response and release the connection.711 Automatically called if the response body is read to completion.712 """713 if not self.is_closed:714 self.is_closed = True715 if self.on_close is not None:716 await self.on_close()717718 @property719 def is_redirect(self) -> bool:720 return (721 self.status_code722 in (723 codes.moved_permanently,724 codes.found,725 codes.see_other,726 codes.temporary_redirect,727 codes.permanent_redirect,728 )729 and "location" in self.headers730 )731732 def __repr__(self) -> str:733 class_name = self.__class__.__name__734 return f"<{class_name}({self.status_code}, {self.reason_phrase!r})>"735736 def raise_for_status(self) -> None:737 """738 Raise the `HttpError` if one occurred.739 """740 message = (741 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"742 "For more information check: https://httpstatuses.com/{0.status_code}"743 )744745 if 400 <= self.status_code < 500:746 message = message.format(self, error_type="Client Error")747 elif 500 <= self.status_code < 600:748 message = message.format(self, error_type="Server Error")749 else:750 message = ""751752 if message:753 raise HttpError(message)