models.py
This file
Path
httpcore/models.py
839 lines · 25.7 KiB · Python
Last changed by
Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
History of this fileTake it
1import asyncio2import cgi3import typing4from urllib.parse import parse_qsl, urlencode56import chardet7import rfc398689from .decoders import (10 ACCEPT_ENCODING,11 SUPPORTED_DECODERS,12 Decoder,13 IdentityDecoder,14 MultiDecoder,15)16from .exceptions import (17 HttpError,18 InvalidURL,19 ResponseClosed,20 ResponseNotRead,21 StreamConsumed,22)23from .status_codes import codes24from .utils import (25 get_reason_phrase,26 is_known_encoding,27 normalize_header_key,28 normalize_header_value,29)3031URLTypes = typing.Union["URL", str]3233QueryParamTypes = typing.Union[34 "QueryParams",35 typing.Mapping[str, str],36 typing.List[typing.Tuple[typing.Any, typing.Any]],37 str,38]3940HeaderTypes = typing.Union[41 "Headers",42 typing.Dict[typing.AnyStr, typing.AnyStr],43 typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],44]4546AuthTypes = typing.Union[47 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],48 typing.Callable[["Request"], "Request"],49]5051RequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]5253ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]545556class URL:57 def __init__(58 self,59 url: URLTypes,60 allow_relative: bool = False,61 query_params: QueryParamTypes = None,62 ) -> None:63 if isinstance(url, rfc3986.uri.URIReference):64 self.components = url65 elif isinstance(url, str):66 self.components = rfc3986.api.uri_reference(url)67 else:68 self.components = url.components6970 # Handle IDNA domain names.71 if self.components.authority:72 idna_authority = self.components.authority.encode("idna").decode("ascii")73 if idna_authority != self.components.authority:74 self.components = self.components.copy_with(authority=idna_authority)7576 # Normalize scheme and domain name.77 self.components = self.components.normalize()7879 # Add any query parameters.80 if query_params:81 query_string = str(QueryParams(query_params))82 self.components = self.components.copy_with(query=query_string)8384 # Enforce absolute URLs by default.85 if not allow_relative:86 if not self.scheme:87 raise InvalidURL("No scheme included in URL.")88 if self.scheme not in ("http", "https"):89 raise InvalidURL('URL scheme must be "http" or "https".')90 if not self.host:91 raise InvalidURL("No host included in URL.")9293 @property94 def scheme(self) -> str:95 return self.components.scheme or ""9697 @property98 def authority(self) -> str:99 return self.components.authority or ""100101 @property102 def username(self) -> str:103 userinfo = self.components.userinfo or ""104 return userinfo.partition(":")[0]105106 @property107 def password(self) -> str:108 userinfo = self.components.userinfo or ""109 return userinfo.partition(":")[2]110111 @property112 def host(self) -> str:113 return self.components.host or ""114115 @property116 def port(self) -> int:117 port = self.components.port118 if port is None:119 return {"https": 443, "http": 80}[self.scheme]120 return int(port)121122 @property123 def path(self) -> str:124 return self.components.path or "/"125126 @property127 def query(self) -> str:128 return self.components.query or ""129130 @property131 def full_path(self) -> str:132 path = self.path133 if self.query:134 path += "?" + self.query135 return path136137 @property138 def fragment(self) -> str:139 return self.components.fragment or ""140141 @property142 def is_ssl(self) -> bool:143 return self.components.scheme == "https"144145 @property146 def is_absolute_url(self) -> bool:147 """148 Return `True` for absolute URLs such as 'http://example.com/path',149 and `False` for relative URLs such as '/path'.150 """151 # We don't use rfc3986's `is_absolute` because it treats152 # URLs with a fragment portion as not absolute.153 # What we actually care about is if the URL provides154 # a scheme and hostname to which connections should be made.155 return self.components.scheme and self.components.host156157 @property158 def is_relative_url(self) -> bool:159 return not self.is_absolute_url160161 @property162 def origin(self) -> "Origin":163 return Origin(self)164165 def copy_with(self, **kwargs: typing.Any) -> "URL":166 return URL(self.components.copy_with(**kwargs))167168 def resolve_with(self, base_url: URLTypes) -> "URL":169 """170 Return an absolute URL, using base_url as the base.171 """172 # We drop any fragment portion, because RFC 3986 strictly173 # treats URLs with a fragment portion as not being absolute URLs.174 base_url = URL(base_url).copy_with(fragment=None)175 return URL(self.components.resolve_with(base_url.components))176177 def __hash__(self) -> int:178 return hash(str(self))179180 def __eq__(self, other: typing.Any) -> bool:181 return isinstance(other, URL) and str(self) == str(other)182183 def __str__(self) -> str:184 return self.components.unsplit()185186 def __repr__(self) -> str:187 class_name = self.__class__.__name__188 url_str = str(self)189 return f"{class_name}({url_str!r})"190191192class Origin:193 """194 The URL scheme and authority information, as a comparable, hashable object.195 """196197 def __init__(self, url: URLTypes) -> None:198 if not isinstance(url, URL):199 url = URL(url)200 self.is_ssl = url.is_ssl201 self.host = url.host202 self.port = url.port203204 def __eq__(self, other: typing.Any) -> bool:205 return (206 isinstance(other, self.__class__)207 and self.is_ssl == other.is_ssl208 and self.host == other.host209 and self.port == other.port210 )211212 def __hash__(self) -> int:213 return hash((self.is_ssl, self.host, self.port))214215216class QueryParams(typing.Mapping[str, str]):217 """218 URL query parameters, as a multi-dict.219 """220221 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:222 assert len(args) < 2, "Too many arguments."223 assert not (args and kwargs), "Cannot mix named and unnamed arguments."224225 value = args[0] if args else kwargs226227 if isinstance(value, str):228 items = parse_qsl(value)229 elif isinstance(value, QueryParams):230 items = value.multi_items()231 elif isinstance(value, list):232 items = value233 else:234 items = value.items() # type: ignore235236 self._list = [(str(k), str(v)) for k, v in items]237 self._dict = {str(k): str(v) for k, v in items}238239 def getlist(self, key: typing.Any) -> typing.List[str]:240 return [item_value for item_key, item_value in self._list if item_key == key]241242 def keys(self) -> typing.KeysView:243 return self._dict.keys()244245 def values(self) -> typing.ValuesView:246 return self._dict.values()247248 def items(self) -> typing.ItemsView:249 return self._dict.items()250251 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:252 return list(self._list)253254 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:255 if key in self._dict:256 return self._dict[key]257 return default258259 def __getitem__(self, key: typing.Any) -> str:260 return self._dict[key]261262 def __contains__(self, key: typing.Any) -> bool:263 return key in self._dict264265 def __iter__(self) -> typing.Iterator[typing.Any]:266 return iter(self.keys())267268 def __len__(self) -> int:269 return len(self._dict)270271 def __eq__(self, other: typing.Any) -> bool:272 if not isinstance(other, self.__class__):273 return False274 return sorted(self._list) == sorted(other._list)275276 def __str__(self) -> str:277 return urlencode(self._list)278279 def __repr__(self) -> str:280 class_name = self.__class__.__name__281 query_string = str(self)282 return f"{class_name}({query_string!r})"283284285class Headers(typing.MutableMapping[str, str]):286 """287 HTTP headers, as a case-insensitive multi-dict.288 """289290 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:291 if headers is None:292 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]293 elif isinstance(headers, Headers):294 self._list = list(headers.raw)295 elif isinstance(headers, dict):296 self._list = [297 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))298 for k, v in headers.items()299 ]300 else:301 self._list = [302 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))303 for k, v in headers304 ]305 self._encoding = encoding306307 @property308 def encoding(self) -> str:309 """310 Header encoding is mandated as ascii, but we allow fallbacks to utf-8311 or iso-8859-1.312 """313 if self._encoding is None:314 for encoding in ["ascii", "utf-8"]:315 for key, value in self.raw:316 try:317 key.decode(encoding)318 value.decode(encoding)319 except UnicodeDecodeError:320 break321 else:322 # The else block runs if 'break' did not occur, meaning323 # all values fitted the encoding.324 self._encoding = encoding325 break326 else:327 # The ISO-8859-1 encoding covers all 256 code points in a byte,328 # so will never raise decode errors.329 self._encoding = "iso-8859-1"330 return self._encoding331332 @encoding.setter333 def encoding(self, value: str) -> None:334 self._encoding = value335336 @property337 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:338 """339 Returns a list of the raw header items, as byte pairs.340 May be mutated in-place.341 """342 return self._list343344 def keys(self) -> typing.List[str]: # type: ignore345 return [key.decode(self.encoding) for key, value in self._list]346347 def values(self) -> typing.List[str]: # type: ignore348 return [value.decode(self.encoding) for key, value in self._list]349350 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore351 return [352 (key.decode(self.encoding), value.decode(self.encoding))353 for key, value in self._list354 ]355356 def get(self, key: str, default: typing.Any = None) -> typing.Any:357 try:358 return self[key]359 except KeyError:360 return default361362 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:363 """364 Return multiple header values.365 """366 get_header_key = key.lower().encode(self.encoding)367368 values = [369 item_value.decode(self.encoding)370 for item_key, item_value in self._list371 if item_key == get_header_key372 ]373374 if not split_commas:375 return values376377 split_values = []378 for value in values:379 split_values.extend([item.strip() for item in value.split(",")])380 return split_values381382 def __getitem__(self, key: str) -> str:383 """384 Return a single header value.385386 If there are multiple headers with the same key, then we concatenate387 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2388 """389 normalized_key = key.lower().encode(self.encoding)390391 items = []392 for header_key, header_value in self._list:393 if header_key == normalized_key:394 items.append(header_value.decode(self.encoding))395396 if items:397 return ", ".join(items)398399 raise KeyError(key)400401 def __setitem__(self, key: str, value: str) -> None:402 """403 Set the header `key` to `value`, removing any duplicate entries.404 Retains insertion order.405 """406 set_key = key.lower().encode(self.encoding)407 set_value = value.encode(self.encoding)408409 found_indexes = []410 for idx, (item_key, item_value) in enumerate(self._list):411 if item_key == set_key:412 found_indexes.append(idx)413414 for idx in reversed(found_indexes[1:]):415 del self._list[idx]416417 if found_indexes:418 idx = found_indexes[0]419 self._list[idx] = (set_key, set_value)420 else:421 self._list.append((set_key, set_value))422423 def __delitem__(self, key: str) -> None:424 """425 Remove the header `key`.426 """427 del_key = key.lower().encode(self.encoding)428429 pop_indexes = []430 for idx, (item_key, item_value) in enumerate(self._list):431 if item_key == del_key:432 pop_indexes.append(idx)433434 for idx in reversed(pop_indexes):435 del self._list[idx]436437 def __contains__(self, key: typing.Any) -> bool:438 get_header_key = key.lower().encode(self.encoding)439 for header_key, header_value in self._list:440 if header_key == get_header_key:441 return True442 return False443444 def __iter__(self) -> typing.Iterator[typing.Any]:445 return iter(self.keys())446447 def __len__(self) -> int:448 return len(self._list)449450 def __eq__(self, other: typing.Any) -> bool:451 if not isinstance(other, Headers):452 return False453 return sorted(self._list) == sorted(other._list)454455 def __repr__(self) -> str:456 class_name = self.__class__.__name__457458 encoding_str = ""459 if self.encoding != "ascii":460 encoding_str = f", encoding={self.encoding!r}"461462 as_dict = dict(self.items())463 if len(as_dict) == len(self):464 return f"{class_name}({as_dict!r}{encoding_str})"465 as_list = self.items()466 return f"{class_name}({as_list!r}{encoding_str})"467468469class Request:470 def __init__(471 self,472 method: str,473 url: typing.Union[str, URL],474 *,475 data: RequestData = b"",476 query_params: QueryParamTypes = None,477 headers: HeaderTypes = None,478 ):479 self.method = method.upper()480 self.url = URL(url, query_params=query_params)481 self.headers = Headers(headers)482483 if isinstance(data, bytes):484 self.is_streaming = False485 self.content = data486 elif isinstance(data, dict):487 self.is_streaming = False488 self.content = urlencode(data, doseq=True).encode("utf-8")489 self.headers["Content-Type"] = "application/x-www-form-urlencoded"490 else:491 self.is_streaming = True492 self.content_aiter = data493494 async def read(self) -> bytes:495 """496 Read and return the response content.497 """498 if not hasattr(self, "content"):499 self.content = b"".join([part async for part in self.stream()])500 return self.content501502 async def stream(self) -> typing.AsyncIterator[bytes]:503 if self.is_streaming:504 async for part in self.content_aiter:505 yield part506 elif self.content:507 yield self.content508509 def prepare(self) -> None:510 """511 Adds in any default headers. When using the `Client`, this will512 end up being called into by the `prepare_request()` stage.513514 You can omit this behavior by calling `Client.send()` with an515 explicitly built `Request` instance.516 """517 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]518519 has_host = "host" in self.headers520 has_content_length = (521 "content-length" in self.headers or "transfer-encoding" in self.headers522 )523 has_accept_encoding = "accept-encoding" in self.headers524525 if not has_host and self.url.authority:526 auto_headers.append((b"host", self.url.authority.encode("ascii")))527 if not has_content_length:528 if self.is_streaming:529 auto_headers.append((b"transfer-encoding", b"chunked"))530 elif self.content:531 content_length = str(len(self.content)).encode()532 auto_headers.append((b"content-length", content_length))533 if not has_accept_encoding:534 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))535536 for item in reversed(auto_headers):537 self.headers.raw.insert(0, item)538539 def __repr__(self) -> str:540 class_name = self.__class__.__name__541 url = str(self.url)542 return f"<{class_name}({self.method!r}, {url!r})>"543544545class Response:546 def __init__(547 self,548 status_code: int,549 *,550 reason_phrase: str = None,551 protocol: str = None,552 headers: HeaderTypes = None,553 content: ResponseContent = b"",554 on_close: typing.Callable = None,555 request: Request = None,556 history: typing.List["Response"] = None,557 ):558 try:559 # Use a StatusCode IntEnum if possible, for a nicer representation.560 self.status_code = codes(status_code) # type: int561 except ValueError:562 self.status_code = status_code563 self.reason_phrase = reason_phrase or get_reason_phrase(status_code)564 self.protocol = protocol565 self.headers = Headers(headers)566567 if isinstance(content, bytes):568 self.is_closed = True569 self.is_stream_consumed = True570 self._raw_content = content571 else:572 self.is_closed = False573 self.is_stream_consumed = False574 self._raw_stream = content575576 self.on_close = on_close577 self.request = request578 self.history = [] if history is None else list(history)579 self.next = None # typing.Optional[typing.Callable]580581 @property582 def url(self) -> typing.Optional[URL]:583 """584 Returns the URL for which the request was made.585586 Requires that `request` was provided when instantiating the response.587 """588 return None if self.request is None else self.request.url589590 @property591 def content(self) -> bytes:592 if not hasattr(self, "_content"):593 if hasattr(self, "_raw_content"):594 content = self.decoder.decode(self._raw_content)595 content += self.decoder.flush()596 self._content = content597 else:598 raise ResponseNotRead()599 return self._content600601 @property602 def text(self) -> str:603 if not hasattr(self, "_text"):604 content = self.content605 if not content:606 self._text = ""607 else:608 encoding = self.encoding609 self._text = content.decode(encoding, errors="replace")610 return self._text611612 @property613 def encoding(self) -> str:614 if not hasattr(self, "_encoding"):615 encoding = self.charset_encoding616 if encoding is None or not is_known_encoding(encoding):617 encoding = self.apparent_encoding618 if encoding is None or not is_known_encoding(encoding):619 encoding = "utf-8"620 self._encoding = encoding621 return self._encoding622623 @encoding.setter624 def encoding(self, value: str) -> None:625 self._encoding = value626627 @property628 def charset_encoding(self) -> typing.Optional[str]:629 """630 Return the encoding, as specified by the Content-Type header.631 """632 content_type = self.headers.get("Content-Type")633 if content_type is None:634 return None635636 parsed = cgi.parse_header(content_type)637 media_type, params = parsed[0], parsed[-1]638 if "charset" in params:639 return params["charset"].strip("'\"")640641 # RFC 2616 specifies that 'iso-8859-1' should be used as the default642 # for 'text/*' media types, if no charset is provided.643 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1644 if media_type.startswith("text/"):645 return "iso-8859-1"646647 return None648649 @property650 def apparent_encoding(self) -> typing.Optional[str]:651 """652 Return the encoding, as it appears to autodetection.653 """654 return chardet.detect(self.content)["encoding"]655656 @property657 def decoder(self) -> Decoder:658 """659 Returns a decoder instance which can be used to decode the raw byte660 content, depending on the Content-Encoding used in the response.661 """662 if not hasattr(self, "_decoder"):663 decoders = [] # type: typing.List[Decoder]664 values = self.headers.getlist("content-encoding", split_commas=True)665 for value in values:666 value = value.strip().lower()667 decoder_cls = SUPPORTED_DECODERS[value]668 decoders.append(decoder_cls())669670 if len(decoders) == 1:671 self._decoder = decoders[0]672 elif len(decoders) > 1:673 self._decoder = MultiDecoder(decoders)674 else:675 self._decoder = IdentityDecoder()676677 return self._decoder678679 async def read(self) -> bytes:680 """681 Read and return the response content.682 """683 if not hasattr(self, "_content"):684 self._content = b"".join([part async for part in self.stream()])685 return self._content686687 async def stream(self) -> typing.AsyncIterator[bytes]:688 """689 A byte-iterator over the decoded response content.690 This allows us to handle gzip, deflate, and brotli encoded responses.691 """692 if hasattr(self, "_content"):693 yield self._content694 else:695 async for chunk in self.raw():696 yield self.decoder.decode(chunk)697 yield self.decoder.flush()698699 async def raw(self) -> typing.AsyncIterator[bytes]:700 """701 A byte-iterator over the raw response content.702 """703 if hasattr(self, "_raw_content"):704 yield self._raw_content705 else:706 if self.is_stream_consumed:707 raise StreamConsumed()708 if self.is_closed:709 raise ResponseClosed()710711 self.is_stream_consumed = True712 async for part in self._raw_stream:713 yield part714 await self.close()715716 async def close(self) -> None:717 """718 Close the response and release the connection.719 Automatically called if the response body is read to completion.720 """721 if not self.is_closed:722 self.is_closed = True723 if self.on_close is not None:724 await self.on_close()725726 @property727 def is_redirect(self) -> bool:728 return (729 self.status_code730 in (731 codes.MOVED_PERMANENTLY,732 codes.FOUND,733 codes.SEE_OTHER,734 codes.TEMPORARY_REDIRECT,735 codes.PERMANENT_REDIRECT,736 )737 and "location" in self.headers738 )739740 def raise_for_status(self) -> None:741 """742 Raise the `HttpError` if one occurred.743 """744 message = (745 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"746 "For more information check: https://httpstatuses.com/{0.status_code}"747 )748749 if 400 <= self.status_code < 500:750 message = message.format(self, error_type="Client Error")751 elif 500 <= self.status_code < 600:752 message = message.format(self, error_type="Server Error")753 else:754 message = ""755756 if message:757 raise HttpError(message)758759 def __repr__(self) -> str:760 return f"<Response({self.status_code}, {self.reason_phrase!r})>"761762763class SyncResponse:764 """765 A thread-synchronous response. This class proxies onto a `Response`766 instance, providing standard synchronous interfaces where required.767 """768769 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):770 self._response = response771 self._loop = loop772773 @property774 def status_code(self) -> int:775 return self._response.status_code776777 @property778 def reason_phrase(self) -> str:779 return self._response.reason_phrase780781 @property782 def protocol(self) -> typing.Optional[str]:783 return self._response.protocol784785 @property786 def url(self) -> typing.Optional[URL]:787 return self._response.url788789 @property790 def request(self) -> typing.Optional[Request]:791 return self._response.request792793 @property794 def headers(self) -> Headers:795 return self._response.headers796797 @property798 def content(self) -> bytes:799 return self._response.content800801 @property802 def text(self) -> str:803 return self._response.text804805 @property806 def encoding(self) -> str:807 return self._response.encoding808809 @property810 def is_redirect(self) -> bool:811 return self._response.is_redirect812813 def raise_for_status(self) -> None:814 return self._response.raise_for_status()815816 def read(self) -> bytes:817 return self._loop.run_until_complete(self._response.read())818819 def stream(self) -> typing.Iterator[bytes]:820 inner = self._response.stream()821 while True:822 try:823 yield self._loop.run_until_complete(inner.__anext__())824 except StopAsyncIteration:825 break826827 def raw(self) -> typing.Iterator[bytes]:828 inner = self._response.raw()829 while True:830 try:831 yield self._loop.run_until_complete(inner.__anext__())832 except StopAsyncIteration:833 break834835 def close(self) -> None:836 return self._loop.run_until_complete(self._response.close())837838 def __repr__(self) -> str:839 return f"<Response({self.status_code}, {self.reason_phrase!r})>"