models.py
This file
Path
httpcore/models.py
824 lines · 25.2 KiB · Python
Last changed by
Include URL.__hash__ in test (#64)Yeray Diaz Diazbefore adoption2e9ab2e
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]4546RequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]4748ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]495051class URL:52 def __init__(53 self,54 url: URLTypes,55 allow_relative: bool = False,56 query_params: QueryParamTypes = None,57 ) -> None:58 if isinstance(url, rfc3986.uri.URIReference):59 self.components = url60 elif isinstance(url, str):61 self.components = rfc3986.api.uri_reference(url)62 else:63 self.components = url.components6465 # Handle IDNA domain names.66 if self.components.authority:67 idna_authority = self.components.authority.encode("idna").decode("ascii")68 if idna_authority != self.components.authority:69 self.components = self.components.copy_with(authority=idna_authority)7071 # Normalize scheme and domain name.72 self.components = self.components.normalize()7374 # Add any query parameters.75 if query_params:76 query_string = str(QueryParams(query_params))77 self.components = self.components.copy_with(query=query_string)7879 # Enforce absolute URLs by default.80 if not allow_relative:81 if not self.scheme:82 raise InvalidURL("No scheme included in URL.")83 if self.scheme not in ("http", "https"):84 raise InvalidURL('URL scheme must be "http" or "https".')85 if not self.host:86 raise InvalidURL("No host included in URL.")8788 @property89 def scheme(self) -> str:90 return self.components.scheme or ""9192 @property93 def authority(self) -> str:94 return self.components.authority or ""9596 @property97 def host(self) -> str:98 return self.components.host or ""99100 @property101 def port(self) -> int:102 port = self.components.port103 if port is None:104 return {"https": 443, "http": 80}[self.scheme]105 return int(port)106107 @property108 def path(self) -> str:109 return self.components.path or "/"110111 @property112 def query(self) -> str:113 return self.components.query or ""114115 @property116 def full_path(self) -> str:117 path = self.path118 if self.query:119 path += "?" + self.query120 return path121122 @property123 def fragment(self) -> str:124 return self.components.fragment or ""125126 @property127 def is_ssl(self) -> bool:128 return self.components.scheme == "https"129130 @property131 def is_absolute_url(self) -> bool:132 """133 Return `True` for absolute URLs such as 'http://example.com/path',134 and `False` for relative URLs such as '/path'.135 """136 # We don't use rfc3986's `is_absolute` because it treats137 # URLs with a fragment portion as not absolute.138 # What we actually care about is if the URL provides139 # a scheme and hostname to which connections should be made.140 return self.components.scheme and self.components.host141142 @property143 def is_relative_url(self) -> bool:144 return not self.is_absolute_url145146 @property147 def origin(self) -> "Origin":148 return Origin(self)149150 def copy_with(self, **kwargs: typing.Any) -> "URL":151 return URL(self.components.copy_with(**kwargs))152153 def resolve_with(self, base_url: URLTypes) -> "URL":154 """155 Return an absolute URL, using base_url as the base.156 """157 # We drop any fragment portion, because RFC 3986 strictly158 # treats URLs with a fragment portion as not being absolute URLs.159 base_url = URL(base_url).copy_with(fragment=None)160 return URL(self.components.resolve_with(base_url.components))161162 def __hash__(self) -> int:163 return hash(str(self))164165 def __eq__(self, other: typing.Any) -> bool:166 return isinstance(other, URL) and str(self) == str(other)167168 def __str__(self) -> str:169 return self.components.unsplit()170171 def __repr__(self) -> str:172 class_name = self.__class__.__name__173 url_str = str(self)174 return f"{class_name}({url_str!r})"175176177class Origin:178 """179 The URL scheme and authority information, as a comparable, hashable object.180 """181182 def __init__(self, url: URLTypes) -> None:183 if not isinstance(url, URL):184 url = URL(url)185 self.is_ssl = url.is_ssl186 self.host = url.host187 self.port = url.port188189 def __eq__(self, other: typing.Any) -> bool:190 return (191 isinstance(other, self.__class__)192 and self.is_ssl == other.is_ssl193 and self.host == other.host194 and self.port == other.port195 )196197 def __hash__(self) -> int:198 return hash((self.is_ssl, self.host, self.port))199200201class QueryParams(typing.Mapping[str, str]):202 """203 URL query parameters, as a multi-dict.204 """205206 def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:207 assert len(args) < 2, "Too many arguments."208 assert not (args and kwargs), "Cannot mix named and unnamed arguments."209210 value = args[0] if args else kwargs211212 if isinstance(value, str):213 items = parse_qsl(value)214 elif isinstance(value, QueryParams):215 items = value.multi_items()216 elif isinstance(value, list):217 items = value218 else:219 items = value.items() # type: ignore220221 self._list = [(str(k), str(v)) for k, v in items]222 self._dict = {str(k): str(v) for k, v in items}223224 def getlist(self, key: typing.Any) -> typing.List[str]:225 return [item_value for item_key, item_value in self._list if item_key == key]226227 def keys(self) -> typing.KeysView:228 return self._dict.keys()229230 def values(self) -> typing.ValuesView:231 return self._dict.values()232233 def items(self) -> typing.ItemsView:234 return self._dict.items()235236 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:237 return list(self._list)238239 def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:240 if key in self._dict:241 return self._dict[key]242 return default243244 def __getitem__(self, key: typing.Any) -> str:245 return self._dict[key]246247 def __contains__(self, key: typing.Any) -> bool:248 return key in self._dict249250 def __iter__(self) -> typing.Iterator[typing.Any]:251 return iter(self.keys())252253 def __len__(self) -> int:254 return len(self._dict)255256 def __eq__(self, other: typing.Any) -> bool:257 if not isinstance(other, self.__class__):258 return False259 return sorted(self._list) == sorted(other._list)260261 def __str__(self) -> str:262 return urlencode(self._list)263264 def __repr__(self) -> str:265 class_name = self.__class__.__name__266 query_string = str(self)267 return f"{class_name}({query_string!r})"268269270class Headers(typing.MutableMapping[str, str]):271 """272 HTTP headers, as a case-insensitive multi-dict.273 """274275 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:276 if headers is None:277 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]278 elif isinstance(headers, Headers):279 self._list = list(headers.raw)280 elif isinstance(headers, dict):281 self._list = [282 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))283 for k, v in headers.items()284 ]285 else:286 self._list = [287 (normalize_header_key(k, encoding), normalize_header_value(v, encoding))288 for k, v in headers289 ]290 self._encoding = encoding291292 @property293 def encoding(self) -> str:294 """295 Header encoding is mandated as ascii, but we allow fallbacks to utf-8296 or iso-8859-1.297 """298 if self._encoding is None:299 for encoding in ["ascii", "utf-8"]:300 for key, value in self.raw:301 try:302 key.decode(encoding)303 value.decode(encoding)304 except UnicodeDecodeError:305 break306 else:307 # The else block runs if 'break' did not occur, meaning308 # all values fitted the encoding.309 self._encoding = encoding310 break311 else:312 # The ISO-8859-1 encoding covers all 256 code points in a byte,313 # so will never raise decode errors.314 self._encoding = "iso-8859-1"315 return self._encoding316317 @encoding.setter318 def encoding(self, value: str) -> None:319 self._encoding = value320321 @property322 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:323 """324 Returns a list of the raw header items, as byte pairs.325 May be mutated in-place.326 """327 return self._list328329 def keys(self) -> typing.List[str]: # type: ignore330 return [key.decode(self.encoding) for key, value in self._list]331332 def values(self) -> typing.List[str]: # type: ignore333 return [value.decode(self.encoding) for key, value in self._list]334335 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore336 return [337 (key.decode(self.encoding), value.decode(self.encoding))338 for key, value in self._list339 ]340341 def get(self, key: str, default: typing.Any = None) -> typing.Any:342 try:343 return self[key]344 except KeyError:345 return default346347 def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:348 """349 Return multiple header values.350 """351 get_header_key = key.lower().encode(self.encoding)352353 values = [354 item_value.decode(self.encoding)355 for item_key, item_value in self._list356 if item_key == get_header_key357 ]358359 if not split_commas:360 return values361362 split_values = []363 for value in values:364 split_values.extend([item.strip() for item in value.split(",")])365 return split_values366367 def __getitem__(self, key: str) -> str:368 """369 Return a single header value.370371 If there are multiple headers with the same key, then we concatenate372 them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2373 """374 normalized_key = key.lower().encode(self.encoding)375376 items = []377 for header_key, header_value in self._list:378 if header_key == normalized_key:379 items.append(header_value.decode(self.encoding))380381 if items:382 return ", ".join(items)383384 raise KeyError(key)385386 def __setitem__(self, key: str, value: str) -> None:387 """388 Set the header `key` to `value`, removing any duplicate entries.389 Retains insertion order.390 """391 set_key = key.lower().encode(self.encoding)392 set_value = value.encode(self.encoding)393394 found_indexes = []395 for idx, (item_key, item_value) in enumerate(self._list):396 if item_key == set_key:397 found_indexes.append(idx)398399 for idx in reversed(found_indexes[1:]):400 del self._list[idx]401402 if found_indexes:403 idx = found_indexes[0]404 self._list[idx] = (set_key, set_value)405 else:406 self._list.append((set_key, set_value))407408 def __delitem__(self, key: str) -> None:409 """410 Remove the header `key`.411 """412 del_key = key.lower().encode(self.encoding)413414 pop_indexes = []415 for idx, (item_key, item_value) in enumerate(self._list):416 if item_key == del_key:417 pop_indexes.append(idx)418419 for idx in reversed(pop_indexes):420 del self._list[idx]421422 def __contains__(self, key: typing.Any) -> bool:423 get_header_key = key.lower().encode(self.encoding)424 for header_key, header_value in self._list:425 if header_key == get_header_key:426 return True427 return False428429 def __iter__(self) -> typing.Iterator[typing.Any]:430 return iter(self.keys())431432 def __len__(self) -> int:433 return len(self._list)434435 def __eq__(self, other: typing.Any) -> bool:436 if not isinstance(other, Headers):437 return False438 return sorted(self._list) == sorted(other._list)439440 def __repr__(self) -> str:441 class_name = self.__class__.__name__442443 encoding_str = ""444 if self.encoding != "ascii":445 encoding_str = f", encoding={self.encoding!r}"446447 as_dict = dict(self.items())448 if len(as_dict) == len(self):449 return f"{class_name}({as_dict!r}{encoding_str})"450 as_list = self.items()451 return f"{class_name}({as_list!r}{encoding_str})"452453454class Request:455 def __init__(456 self,457 method: str,458 url: typing.Union[str, URL],459 *,460 data: RequestData = b"",461 query_params: QueryParamTypes = None,462 headers: HeaderTypes = None,463 ):464 self.method = method.upper()465 self.url = URL(url, query_params=query_params)466 self.headers = Headers(headers)467468 if isinstance(data, bytes):469 self.is_streaming = False470 self.content = data471 elif isinstance(data, dict):472 self.is_streaming = False473 self.content = urlencode(data, doseq=True).encode("utf-8")474 self.headers["Content-Type"] = "application/x-www-form-urlencoded"475 else:476 self.is_streaming = True477 self.content_aiter = data478479 async def read(self) -> bytes:480 """481 Read and return the response content.482 """483 if not hasattr(self, "content"):484 self.content = b"".join([part async for part in self.stream()])485 return self.content486487 async def stream(self) -> typing.AsyncIterator[bytes]:488 if self.is_streaming:489 async for part in self.content_aiter:490 yield part491 elif self.content:492 yield self.content493494 def prepare(self) -> None:495 """496 Adds in any default headers. When using the `Client`, this will497 end up being called into by the `prepare_request()` stage.498499 You can omit this behavior by calling `Client.send()` with an500 explicitly built `Request` instance.501 """502 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]503504 has_host = "host" in self.headers505 has_content_length = (506 "content-length" in self.headers or "transfer-encoding" in self.headers507 )508 has_accept_encoding = "accept-encoding" in self.headers509510 if not has_host and self.url.authority:511 auto_headers.append((b"host", self.url.authority.encode("ascii")))512 if not has_content_length:513 if self.is_streaming:514 auto_headers.append((b"transfer-encoding", b"chunked"))515 elif self.content:516 content_length = str(len(self.content)).encode()517 auto_headers.append((b"content-length", content_length))518 if not has_accept_encoding:519 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))520521 for item in reversed(auto_headers):522 self.headers.raw.insert(0, item)523524 def __repr__(self) -> str:525 class_name = self.__class__.__name__526 url = str(self.url)527 return f"<{class_name}({self.method!r}, {url!r})>"528529530class Response:531 def __init__(532 self,533 status_code: int,534 *,535 reason_phrase: str = None,536 protocol: str = None,537 headers: HeaderTypes = None,538 content: ResponseContent = b"",539 on_close: typing.Callable = None,540 request: Request = None,541 history: typing.List["Response"] = None,542 ):543 try:544 # Use a StatusCode IntEnum if possible, for a nicer representation.545 self.status_code = codes(status_code) # type: int546 except ValueError:547 self.status_code = status_code548 self.reason_phrase = reason_phrase or get_reason_phrase(status_code)549 self.protocol = protocol550 self.headers = Headers(headers)551552 if isinstance(content, bytes):553 self.is_closed = True554 self.is_stream_consumed = True555 self._raw_content = content556 else:557 self.is_closed = False558 self.is_stream_consumed = False559 self._raw_stream = content560561 self.on_close = on_close562 self.request = request563 self.history = [] if history is None else list(history)564 self.next = None # typing.Optional[typing.Callable]565566 @property567 def url(self) -> typing.Optional[URL]:568 """569 Returns the URL for which the request was made.570571 Requires that `request` was provided when instantiating the response.572 """573 return None if self.request is None else self.request.url574575 @property576 def content(self) -> bytes:577 if not hasattr(self, "_content"):578 if hasattr(self, "_raw_content"):579 content = self.decoder.decode(self._raw_content)580 content += self.decoder.flush()581 self._content = content582 else:583 raise ResponseNotRead()584 return self._content585586 @property587 def text(self) -> str:588 if not hasattr(self, "_text"):589 content = self.content590 if not content:591 self._text = ""592 else:593 encoding = self.encoding594 self._text = content.decode(encoding, errors="replace")595 return self._text596597 @property598 def encoding(self) -> str:599 if not hasattr(self, "_encoding"):600 encoding = self.charset_encoding601 if encoding is None or not is_known_encoding(encoding):602 encoding = self.apparent_encoding603 if encoding is None or not is_known_encoding(encoding):604 encoding = "utf-8"605 self._encoding = encoding606 return self._encoding607608 @encoding.setter609 def encoding(self, value: str) -> None:610 self._encoding = value611612 @property613 def charset_encoding(self) -> typing.Optional[str]:614 """615 Return the encoding, as specified by the Content-Type header.616 """617 content_type = self.headers.get("Content-Type")618 if content_type is None:619 return None620621 parsed = cgi.parse_header(content_type)622 media_type, params = parsed[0], parsed[-1]623 if "charset" in params:624 return params["charset"].strip("'\"")625626 # RFC 2616 specifies that 'iso-8859-1' should be used as the default627 # for 'text/*' media types, if no charset is provided.628 # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1629 if media_type.startswith("text/"):630 return "iso-8859-1"631632 return None633634 @property635 def apparent_encoding(self) -> typing.Optional[str]:636 """637 Return the encoding, as it appears to autodetection.638 """639 return chardet.detect(self.content)["encoding"]640641 @property642 def decoder(self) -> Decoder:643 """644 Returns a decoder instance which can be used to decode the raw byte645 content, depending on the Content-Encoding used in the response.646 """647 if not hasattr(self, "_decoder"):648 decoders = [] # type: typing.List[Decoder]649 values = self.headers.getlist("content-encoding", split_commas=True)650 for value in values:651 value = value.strip().lower()652 decoder_cls = SUPPORTED_DECODERS[value]653 decoders.append(decoder_cls())654655 if len(decoders) == 1:656 self._decoder = decoders[0]657 elif len(decoders) > 1:658 self._decoder = MultiDecoder(decoders)659 else:660 self._decoder = IdentityDecoder()661662 return self._decoder663664 async def read(self) -> bytes:665 """666 Read and return the response content.667 """668 if not hasattr(self, "_content"):669 self._content = b"".join([part async for part in self.stream()])670 return self._content671672 async def stream(self) -> typing.AsyncIterator[bytes]:673 """674 A byte-iterator over the decoded response content.675 This allows us to handle gzip, deflate, and brotli encoded responses.676 """677 if hasattr(self, "_content"):678 yield self._content679 else:680 async for chunk in self.raw():681 yield self.decoder.decode(chunk)682 yield self.decoder.flush()683684 async def raw(self) -> typing.AsyncIterator[bytes]:685 """686 A byte-iterator over the raw response content.687 """688 if hasattr(self, "_raw_content"):689 yield self._raw_content690 else:691 if self.is_stream_consumed:692 raise StreamConsumed()693 if self.is_closed:694 raise ResponseClosed()695696 self.is_stream_consumed = True697 async for part in self._raw_stream:698 yield part699 await self.close()700701 async def close(self) -> None:702 """703 Close the response and release the connection.704 Automatically called if the response body is read to completion.705 """706 if not self.is_closed:707 self.is_closed = True708 if self.on_close is not None:709 await self.on_close()710711 @property712 def is_redirect(self) -> bool:713 return (714 self.status_code715 in (716 codes.MOVED_PERMANENTLY,717 codes.FOUND,718 codes.SEE_OTHER,719 codes.TEMPORARY_REDIRECT,720 codes.PERMANENT_REDIRECT,721 )722 and "location" in self.headers723 )724725 def raise_for_status(self) -> None:726 """727 Raise the `HttpError` if one occurred.728 """729 message = (730 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"731 "For more information check: https://httpstatuses.com/{0.status_code}"732 )733734 if 400 <= self.status_code < 500:735 message = message.format(self, error_type="Client Error")736 elif 500 <= self.status_code < 600:737 message = message.format(self, error_type="Server Error")738 else:739 message = ""740741 if message:742 raise HttpError(message)743744 def __repr__(self) -> str:745 return f"<Response({self.status_code}, {self.reason_phrase!r})>"746747748class SyncResponse:749 """750 A thread-synchronous response. This class proxies onto a `Response`751 instance, providing standard synchronous interfaces where required.752 """753754 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):755 self._response = response756 self._loop = loop757758 @property759 def status_code(self) -> int:760 return self._response.status_code761762 @property763 def reason_phrase(self) -> str:764 return self._response.reason_phrase765766 @property767 def protocol(self) -> typing.Optional[str]:768 return self._response.protocol769770 @property771 def url(self) -> typing.Optional[URL]:772 return self._response.url773774 @property775 def request(self) -> typing.Optional[Request]:776 return self._response.request777778 @property779 def headers(self) -> Headers:780 return self._response.headers781782 @property783 def content(self) -> bytes:784 return self._response.content785786 @property787 def text(self) -> str:788 return self._response.text789790 @property791 def encoding(self) -> str:792 return self._response.encoding793794 @property795 def is_redirect(self) -> bool:796 return self._response.is_redirect797798 def raise_for_status(self) -> None:799 return self._response.raise_for_status()800801 def read(self) -> bytes:802 return self._loop.run_until_complete(self._response.read())803804 def stream(self) -> typing.Iterator[bytes]:805 inner = self._response.stream()806 while True:807 try:808 yield self._loop.run_until_complete(inner.__anext__())809 except StopAsyncIteration:810 break811812 def raw(self) -> typing.Iterator[bytes]:813 inner = self._response.raw()814 while True:815 try:816 yield self._loop.run_until_complete(inner.__anext__())817 except StopAsyncIteration:818 break819820 def close(self) -> None:821 return self._loop.run_until_complete(self._response.close())822823 def __repr__(self) -> str:824 return f"<Response({self.status_code}, {self.reason_phrase!r})>"