Skip to content
Myr

models.py

This file

Path

httpcore/models.py

746 lines · 23.1 KiB · Python

Last changed by

Improve class __repr__Tom Christiebefore adoption666d5a8

History of this file

Take 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]4647ByteOrByteStream = typing.Union[bytes, typing.AsyncIterator[bytes]]484950class URL:51    def __init__(52        self,53        url: URLTypes,54        allow_relative: bool = False,55        query_params: QueryParamTypes = None,56    ) -> None:57        if isinstance(url, rfc3986.uri.URIReference):58            self.components = url59        elif isinstance(url, str):60            self.components = rfc3986.api.uri_reference(url)61        else:62            self.components = url.components6364        # Handle IDNA domain names.65        if self.components.authority:66            idna_authority = self.components.authority.encode("idna").decode("ascii")67            if idna_authority != self.components.authority:68                self.components = self.components.copy_with(authority=idna_authority)6970        # Normalize scheme and domain name.71        self.components = self.components.normalize()7273        # Add any query parameters.74        if query_params:75            query_string = str(QueryParams(query_params))76            self.components = self.components.copy_with(query=query_string)7778        # Enforce absolute URLs by default.79        if not allow_relative:80            if not self.scheme:81                raise InvalidURL("No scheme included in URL.")82            if self.scheme not in ("http", "https"):83                raise InvalidURL('URL scheme must be "http" or "https".')84            if not self.host:85                raise InvalidURL("No host included in URL.")8687    @property88    def scheme(self) -> str:89        return self.components.scheme or ""9091    @property92    def authority(self) -> str:93        return self.components.authority or ""9495    @property96    def host(self) -> str:97        return self.components.host or ""9899    @property100    def port(self) -> int:101        port = self.components.port102        if port is None:103            return {"https": 443, "http": 80}[self.scheme]104        return int(port)105106    @property107    def path(self) -> str:108        return self.components.path or "/"109110    @property111    def query(self) -> str:112        return self.components.query or ""113114    @property115    def full_path(self) -> str:116        path = self.path117        if self.query:118            path += "?" + self.query119        return path120121    @property122    def fragment(self) -> str:123        return self.components.fragment or ""124125    @property126    def is_ssl(self) -> bool:127        return self.components.scheme == "https"128129    @property130    def is_absolute_url(self) -> bool:131        """132        Return `True` for absolute URLs such as 'http://example.com/path',133        and `False` for relative URLs such as '/path'.134        """135        # We don't use rfc3986's `is_absolute` because it treats136        # URLs with a fragment portion as not absolute.137        # What we actually care about is if the URL provides138        # a scheme and hostname to which connections should be made.139        return self.components.scheme and self.components.host140141    @property142    def is_relative_url(self) -> bool:143        return not self.is_absolute_url144145    @property146    def origin(self) -> "Origin":147        return Origin(self)148149    def copy_with(self, **kwargs: typing.Any) -> "URL":150        return URL(self.components.copy_with(**kwargs))151152    def resolve_with(self, base_url: URLTypes) -> "URL":153        """154        Return an absolute URL, using base_url as the base.155        """156        # We drop any fragment portion, because RFC 3986 strictly157        # treats URLs with a fragment portion as not being absolute URLs.158        base_url = URL(base_url).copy_with(fragment=None)159        return URL(self.components.resolve_with(base_url.components))160161    def __hash__(self) -> int:162        return hash(str(self))163164    def __eq__(self, other: typing.Any) -> bool:165        return isinstance(other, URL) and str(self) == str(other)166167    def __str__(self) -> str:168        return self.components.unsplit()169170    def __repr__(self) -> str:171        class_name = self.__class__.__name__172        url_str = str(self)173        return f"{class_name}({url_str!r})"174175176class Origin:177    """178    The URL scheme and authority information, as a comparable, hashable object.179    """180181    def __init__(self, url: URLTypes) -> None:182        if not isinstance(url, URL):183            url = URL(url)184        self.is_ssl = url.is_ssl185        self.host = url.host186        self.port = url.port187188    def __eq__(self, other: typing.Any) -> bool:189        return (190            isinstance(other, self.__class__)191            and self.is_ssl == other.is_ssl192            and self.host == other.host193            and self.port == other.port194        )195196    def __hash__(self) -> int:197        return hash((self.is_ssl, self.host, self.port))198199200class QueryParams(typing.Mapping):201    """202    URL query parameters, as a multi-dict.203    """204205    def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:206        assert len(args) < 2, "Too many arguments."207        assert not (args and kwargs), "Cannot mix named and unnamed arguments."208209        value = args[0] if args else kwargs210211        if isinstance(value, str):212            items = parse_qsl(value)213        elif isinstance(value, QueryParams):214            items = value.multi_items()215        elif isinstance(value, list):216            items = value217        else:218            items = value.items()  # type: ignore219220        self._list = [(str(k), str(v)) for k, v in items]221        self._dict = {str(k): str(v) for k, v in items}222223    def getlist(self, key: typing.Any) -> typing.List[str]:224        return [item_value for item_key, item_value in self._list if item_key == key]225226    def keys(self) -> typing.KeysView:227        return self._dict.keys()228229    def values(self) -> typing.ValuesView:230        return self._dict.values()231232    def items(self) -> typing.ItemsView:233        return self._dict.items()234235    def multi_items(self) -> typing.List[typing.Tuple[str, str]]:236        return list(self._list)237238    def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:239        if key in self._dict:240            return self._dict[key]241        return default242243    def __getitem__(self, key: typing.Any) -> str:244        return self._dict[key]245246    def __contains__(self, key: typing.Any) -> bool:247        return key in self._dict248249    def __iter__(self) -> typing.Iterator[typing.Any]:250        return iter(self.keys())251252    def __len__(self) -> int:253        return len(self._dict)254255    def __eq__(self, other: typing.Any) -> bool:256        if not isinstance(other, self.__class__):257            return False258        return sorted(self._list) == sorted(other._list)259260    def __str__(self) -> str:261        return urlencode(self._list)262263    def __repr__(self) -> str:264        class_name = self.__class__.__name__265        query_string = str(self)266        return f"{class_name}({query_string!r})"267268269class Headers(typing.MutableMapping[str, str]):270    """271    HTTP headers, as a case-insensitive multi-dict.272    """273274    def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:275        if headers is None:276            self._list = []  # type: typing.List[typing.Tuple[bytes, bytes]]277        elif isinstance(headers, Headers):278            self._list = list(headers.raw)279        elif isinstance(headers, dict):280            self._list = [281                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))282                for k, v in headers.items()283            ]284        else:285            self._list = [286                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))287                for k, v in headers288            ]289        self._encoding = encoding290291    @property292    def encoding(self) -> str:293        """294        Header encoding is mandated as ascii, but we allow fallbacks to utf-8295        or iso-8859-1.296        """297        if self._encoding is None:298            for encoding in ["ascii", "utf-8"]:299                for key, value in self.raw:300                    try:301                        key.decode(encoding)302                        value.decode(encoding)303                    except UnicodeDecodeError:304                        break305                else:306                    # The else block runs if 'break' did not occur, meaning307                    # all values fitted the encoding.308                    self._encoding = encoding309                    break310            else:311                # The ISO-8859-1 encoding covers all 256 code points in a byte,312                # so will never raise decode errors.313                self._encoding = "iso-8859-1"314        return self._encoding315316    @encoding.setter317    def encoding(self, value: str) -> None:318        self._encoding = value319320    @property321    def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:322        """323        Returns a list of the raw header items, as byte pairs.324        May be mutated in-place.325        """326        return self._list327328    def keys(self) -> typing.List[str]:  # type: ignore329        return [key.decode(self.encoding) for key, value in self._list]330331    def values(self) -> typing.List[str]:  # type: ignore332        return [value.decode(self.encoding) for key, value in self._list]333334    def items(self) -> typing.List[typing.Tuple[str, str]]:  # type: ignore335        return [336            (key.decode(self.encoding), value.decode(self.encoding))337            for key, value in self._list338        ]339340    def get(self, key: str, default: typing.Any = None) -> typing.Any:341        try:342            return self[key]343        except KeyError:344            return default345346    def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:347        """348        Return multiple header values.349        """350        get_header_key = key.lower().encode(self.encoding)351352        values = [353            item_value.decode(self.encoding)354            for item_key, item_value in self._list355            if item_key == get_header_key356        ]357358        if not split_commas:359            return values360361        split_values = []362        for value in values:363            split_values.extend([item.strip() for item in value.split(",")])364        return split_values365366    def __getitem__(self, key: str) -> str:367        """368        Return a single header value.369370        If there are multiple headers with the same key, then we concatenate371        them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2372        """373        normalized_key = key.lower().encode(self.encoding)374375        items = []376        for header_key, header_value in self._list:377            if header_key == normalized_key:378                items.append(header_value.decode(self.encoding))379380        if items:381            return ", ".join(items)382383        raise KeyError(key)384385    def __setitem__(self, key: str, value: str) -> None:386        """387        Set the header `key` to `value`, removing any duplicate entries.388        Retains insertion order.389        """390        set_key = key.lower().encode(self.encoding)391        set_value = value.encode(self.encoding)392393        found_indexes = []394        for idx, (item_key, item_value) in enumerate(self._list):395            if item_key == set_key:396                found_indexes.append(idx)397398        for idx in reversed(found_indexes[1:]):399            del self._list[idx]400401        if found_indexes:402            idx = found_indexes[0]403            self._list[idx] = (set_key, set_value)404        else:405            self._list.append((set_key, set_value))406407    def __delitem__(self, key: str) -> None:408        """409        Remove the header `key`.410        """411        del_key = key.lower().encode(self.encoding)412413        pop_indexes = []414        for idx, (item_key, item_value) in enumerate(self._list):415            if item_key == del_key:416                pop_indexes.append(idx)417418        for idx in reversed(pop_indexes):419            del self._list[idx]420421    def __contains__(self, key: typing.Any) -> bool:422        get_header_key = key.lower().encode(self.encoding)423        for header_key, header_value in self._list:424            if header_key == get_header_key:425                return True426        return False427428    def __iter__(self) -> typing.Iterator[typing.Any]:429        return iter(self.keys())430431    def __len__(self) -> int:432        return len(self._list)433434    def __eq__(self, other: typing.Any) -> bool:435        if not isinstance(other, Headers):436            return False437        return sorted(self._list) == sorted(other._list)438439    def __repr__(self) -> str:440        class_name = self.__class__.__name__441442        encoding_str = ""443        if self.encoding != "ascii":444            encoding_str = f", encoding={self.encoding!r}"445446        as_dict = dict(self.items())447        if len(as_dict) == len(self):448            return f"{class_name}({as_dict!r}{encoding_str})"449        as_list = self.items()450        return f"{class_name}({as_list!r}{encoding_str})"451452453class Request:454    def __init__(455        self,456        method: str,457        url: typing.Union[str, URL],458        *,459        query_params: QueryParamTypes = None,460        headers: HeaderTypes = None,461        content: ByteOrByteStream = b"",462    ):463        self.method = method.upper()464        self.url = URL(url, query_params=query_params)465        if isinstance(content, bytes):466            self.is_streaming = False467            self.content = content468        else:469            self.is_streaming = True470            self.content_aiter = content471        self.headers = Headers(headers)472473    async def read(self) -> bytes:474        """475        Read and return the response content.476        """477        if not hasattr(self, "content"):478            content = b""479            async for part in self.stream():480                content += part481            self.content = content482        return self.content483484    async def stream(self) -> typing.AsyncIterator[bytes]:485        if self.is_streaming:486            async for part in self.content_aiter:487                yield part488        elif self.content:489            yield self.content490491    def prepare(self) -> None:492        """493        Adds in any default headers. When using the `Client`, this will494        end up being called into by the `prepare_request()` stage.495496        You can omit this behavior by calling `Client.send()` with an497        explicitly built `Request` instance.498        """499        auto_headers = []  # type: typing.List[typing.Tuple[bytes, bytes]]500501        has_host = "host" in self.headers502        has_content_length = (503            "content-length" in self.headers or "transfer-encoding" in self.headers504        )505        has_accept_encoding = "accept-encoding" in self.headers506507        if not has_host and self.url.authority:508            auto_headers.append((b"host", self.url.authority.encode("ascii")))509        if not has_content_length:510            if self.is_streaming:511                auto_headers.append((b"transfer-encoding", b"chunked"))512            elif self.content:513                content_length = str(len(self.content)).encode()514                auto_headers.append((b"content-length", content_length))515        if not has_accept_encoding:516            auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))517518        for item in reversed(auto_headers):519            self.headers.raw.insert(0, item)520521    def __repr__(self) -> str:522        class_name = self.__class__.__name__523        url = str(self.url)524        return f"<{class_name}({self.method!r}, {url!r})>"525526527class Response:528    def __init__(529        self,530        status_code: int,531        *,532        reason_phrase: str = None,533        protocol: str = None,534        headers: HeaderTypes = None,535        content: ByteOrByteStream = b"",536        on_close: typing.Callable = None,537        request: Request = None,538        history: typing.List["Response"] = None,539    ):540        try:541            # Use a StatusCode IntEnum if possible, for a nicer representation.542            self.status_code = codes(status_code)  # type: int543        except ValueError:544            self.status_code = status_code545        self.reason_phrase = reason_phrase or get_reason_phrase(status_code)546        self.protocol = protocol547        self.headers = Headers(headers)548549        if isinstance(content, bytes):550            self.is_closed = True551            self.is_stream_consumed = True552            self._raw_content = content553        else:554            self.is_closed = False555            self.is_stream_consumed = False556            self._raw_stream = content557558        self.on_close = on_close559        self.request = request560        self.history = [] if history is None else list(history)561        self.next = None  # typing.Optional[typing.Callable]562563    @property564    def url(self) -> typing.Optional[URL]:565        """566        Returns the URL for which the request was made.567568        Requires that `request` was provided when instantiating the response.569        """570        return None if self.request is None else self.request.url571572    @property573    def content(self) -> bytes:574        if not hasattr(self, "_content"):575            if hasattr(self, "_raw_content"):576                content = self.decoder.decode(self._raw_content)577                content += self.decoder.flush()578                self._content = content579            else:580                raise ResponseNotRead()581        return self._content582583    @property584    def text(self) -> str:585        if not hasattr(self, "_text"):586            content = self.content587            if not content:588                self._text = ""589            else:590                encoding = self.encoding591                self._text = content.decode(encoding, errors="replace")592        return self._text593594    @property595    def encoding(self) -> str:596        if not hasattr(self, "_encoding"):597            encoding = self.charset_encoding598            if encoding is None or not is_known_encoding(encoding):599                encoding = self.apparent_encoding600                if encoding is None or not is_known_encoding(encoding):601                    encoding = "utf-8"602            self._encoding = encoding603        return self._encoding604605    @encoding.setter606    def encoding(self, value: str) -> None:607        self._encoding = value608609    @property610    def charset_encoding(self) -> typing.Optional[str]:611        """612        Return the encoding, as specified by the Content-Type header.613        """614        content_type = self.headers.get("Content-Type")615        if content_type is None:616            return None617618        parsed = cgi.parse_header(content_type)619        media_type, params = parsed[0], parsed[-1]620        if "charset" in params:621            return params["charset"].strip("'\"")622623        # RFC 2616 specifies that 'iso-8859-1' should be used as the default624        # for 'text/*' media types, if no charset is provided.625        # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1626        if media_type.startswith("text/"):627            return "iso-8859-1"628629        return None630631    @property632    def apparent_encoding(self) -> typing.Optional[str]:633        """634        Return the encoding, as it appears to autodetection.635        """636        return chardet.detect(self.content)["encoding"]637638    @property639    def decoder(self) -> Decoder:640        """641        Returns a decoder instance which can be used to decode the raw byte642        content, depending on the Content-Encoding used in the response.643        """644        if not hasattr(self, "_decoder"):645            decoders = []  # type: typing.List[Decoder]646            values = self.headers.getlist("content-encoding", split_commas=True)647            for value in values:648                value = value.strip().lower()649                decoder_cls = SUPPORTED_DECODERS[value]650                decoders.append(decoder_cls())651652            if len(decoders) == 1:653                self._decoder = decoders[0]654            elif len(decoders) > 1:655                self._decoder = MultiDecoder(decoders)656            else:657                self._decoder = IdentityDecoder()658659        return self._decoder660661    async def read(self) -> bytes:662        """663        Read and return the response content.664        """665        if not hasattr(self, "_content"):666            content = b""667            async for part in self.stream():668                content += part669            self._content = content670        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 __repr__(self) -> str:726        class_name = self.__class__.__name__727        return f"<{class_name}({self.status_code}, {self.reason_phrase!r})>"728729    def raise_for_status(self) -> None:730        """731        Raise the `HttpError` if one occurred.732        """733        message = (734            "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"735            "For more information check: https://httpstatuses.com/{0.status_code}"736        )737738        if 400 <= self.status_code < 500:739            message = message.format(self, error_type="Client Error")740        elif 500 <= self.status_code < 600:741            message = message.format(self, error_type="Server Error")742        else:743            message = ""744745        if message:746            raise HttpError(message)