Skip to content
Myr

models.py

This file

Path

httpcore/models.py

742 lines · 23.0 KiB · Python

Last changed by

Add query_params supportTom Christiebefore adoptionfaededa

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    def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:202        assert len(args) < 2, "Too many arguments."203        assert not (args and kwargs), "Cannot mix named and unnamed arguments."204205        value = args[0] if args else kwargs206207        if isinstance(value, str):208            items = parse_qsl(value)209        elif isinstance(value, QueryParams):210            items = value.multi_items()211        elif isinstance(value, list):212            items = value213        else:214            items = value.items()  # type: ignore215216        self._list = [(str(k), str(v)) for k, v in items]217        self._dict = {str(k): str(v) for k, v in items}218219    def getlist(self, key: typing.Any) -> typing.List[str]:220        return [item_value for item_key, item_value in self._list if item_key == key]221222    def keys(self) -> typing.KeysView:223        return self._dict.keys()224225    def values(self) -> typing.ValuesView:226        return self._dict.values()227228    def items(self) -> typing.ItemsView:229        return self._dict.items()230231    def multi_items(self) -> typing.List[typing.Tuple[str, str]]:232        return list(self._list)233234    def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:235        if key in self._dict:236            return self._dict[key]237        return default238239    def __getitem__(self, key: typing.Any) -> str:240        return self._dict[key]241242    def __contains__(self, key: typing.Any) -> bool:243        return key in self._dict244245    def __iter__(self) -> typing.Iterator[typing.Any]:246        return iter(self.keys())247248    def __len__(self) -> int:249        return len(self._dict)250251    def __eq__(self, other: typing.Any) -> bool:252        if not isinstance(other, self.__class__):253            return False254        return sorted(self._list) == sorted(other._list)255256    def __str__(self) -> str:257        return urlencode(self._list)258259    def __repr__(self) -> str:260        class_name = self.__class__.__name__261        query_string = str(self)262        return f"{class_name}({query_string!r})"263264265class Headers(typing.MutableMapping[str, str]):266    """267    HTTP headers, as a case-insensitive multi-dict.268    """269270    def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:271        if headers is None:272            self._list = []  # type: typing.List[typing.Tuple[bytes, bytes]]273        elif isinstance(headers, Headers):274            self._list = list(headers.raw)275        elif isinstance(headers, dict):276            self._list = [277                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))278                for k, v in headers.items()279            ]280        else:281            self._list = [282                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))283                for k, v in headers284            ]285        self._encoding = encoding286287    @property288    def encoding(self) -> str:289        """290        Header encoding is mandated as ascii, but we allow fallbacks to utf-8291        or iso-8859-1.292        """293        if self._encoding is None:294            for encoding in ["ascii", "utf-8"]:295                for key, value in self.raw:296                    try:297                        key.decode(encoding)298                        value.decode(encoding)299                    except UnicodeDecodeError:300                        break301                else:302                    # The else block runs if 'break' did not occur, meaning303                    # all values fitted the encoding.304                    self._encoding = encoding305                    break306            else:307                # The ISO-8859-1 encoding covers all 256 code points in a byte,308                # so will never raise decode errors.309                self._encoding = "iso-8859-1"310        return self._encoding311312    @encoding.setter313    def encoding(self, value: str) -> None:314        self._encoding = value315316    @property317    def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:318        """319        Returns a list of the raw header items, as byte pairs.320        May be mutated in-place.321        """322        return self._list323324    def keys(self) -> typing.List[str]:  # type: ignore325        return [key.decode(self.encoding) for key, value in self._list]326327    def values(self) -> typing.List[str]:  # type: ignore328        return [value.decode(self.encoding) for key, value in self._list]329330    def items(self) -> typing.List[typing.Tuple[str, str]]:  # type: ignore331        return [332            (key.decode(self.encoding), value.decode(self.encoding))333            for key, value in self._list334        ]335336    def get(self, key: str, default: typing.Any = None) -> typing.Any:337        try:338            return self[key]339        except KeyError:340            return default341342    def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:343        """344        Return multiple header values.345        """346        get_header_key = key.lower().encode(self.encoding)347348        values = [349            item_value.decode(self.encoding)350            for item_key, item_value in self._list351            if item_key == get_header_key352        ]353354        if not split_commas:355            return values356357        split_values = []358        for value in values:359            split_values.extend([item.strip() for item in value.split(",")])360        return split_values361362    def __getitem__(self, key: str) -> str:363        """364        Return a single header value.365366        If there are multiple headers with the same key, then we concatenate367        them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2368        """369        normalized_key = key.lower().encode(self.encoding)370371        items = []372        for header_key, header_value in self._list:373            if header_key == normalized_key:374                items.append(header_value.decode(self.encoding))375376        if items:377            return ", ".join(items)378379        raise KeyError(key)380381    def __setitem__(self, key: str, value: str) -> None:382        """383        Set the header `key` to `value`, removing any duplicate entries.384        Retains insertion order.385        """386        set_key = key.lower().encode(self.encoding)387        set_value = value.encode(self.encoding)388389        found_indexes = []390        for idx, (item_key, item_value) in enumerate(self._list):391            if item_key == set_key:392                found_indexes.append(idx)393394        for idx in reversed(found_indexes[1:]):395            del self._list[idx]396397        if found_indexes:398            idx = found_indexes[0]399            self._list[idx] = (set_key, set_value)400        else:401            self._list.append((set_key, set_value))402403    def __delitem__(self, key: str) -> None:404        """405        Remove the header `key`.406        """407        del_key = key.lower().encode(self.encoding)408409        pop_indexes = []410        for idx, (item_key, item_value) in enumerate(self._list):411            if item_key == del_key:412                pop_indexes.append(idx)413414        for idx in reversed(pop_indexes):415            del self._list[idx]416417    def __contains__(self, key: typing.Any) -> bool:418        get_header_key = key.lower().encode(self.encoding)419        for header_key, header_value in self._list:420            if header_key == get_header_key:421                return True422        return False423424    def __iter__(self) -> typing.Iterator[typing.Any]:425        return iter(self.keys())426427    def __len__(self) -> int:428        return len(self._list)429430    def __eq__(self, other: typing.Any) -> bool:431        if not isinstance(other, Headers):432            return False433        return sorted(self._list) == sorted(other._list)434435    def __repr__(self) -> str:436        class_name = self.__class__.__name__437438        encoding_str = ""439        if self.encoding != "ascii":440            encoding_str = f", encoding={self.encoding!r}"441442        as_dict = dict(self.items())443        if len(as_dict) == len(self):444            return f"{class_name}({as_dict!r}{encoding_str})"445        as_list = self.items()446        return f"{class_name}({as_list!r}{encoding_str})"447448449class Request:450    def __init__(451        self,452        method: str,453        url: typing.Union[str, URL],454        *,455        query_params: QueryParamTypes = None,456        headers: HeaderTypes = None,457        content: ByteOrByteStream = b"",458    ):459        self.method = method.upper()460        self.url = URL(url, query_params=query_params)461        if isinstance(content, bytes):462            self.is_streaming = False463            self.content = content464        else:465            self.is_streaming = True466            self.content_aiter = content467        self.headers = Headers(headers)468469    async def read(self) -> bytes:470        """471        Read and return the response content.472        """473        if not hasattr(self, "content"):474            content = b""475            async for part in self.stream():476                content += part477            self.content = content478        return self.content479480    async def stream(self) -> typing.AsyncIterator[bytes]:481        if self.is_streaming:482            async for part in self.content_aiter:483                yield part484        elif self.content:485            yield self.content486487    def prepare(self) -> None:488        """489        Adds in any default headers. When using the `Client`, this will490        end up being called into by the `prepare_request()` stage.491492        You can omit this behavior by calling `Client.send()` with an493        explicitly built `Request` instance.494        """495        auto_headers = []  # type: typing.List[typing.Tuple[bytes, bytes]]496497        has_host = "host" in self.headers498        has_content_length = (499            "content-length" in self.headers or "transfer-encoding" in self.headers500        )501        has_accept_encoding = "accept-encoding" in self.headers502503        if not has_host and self.url.authority:504            auto_headers.append((b"host", self.url.authority.encode("ascii")))505        if not has_content_length:506            if self.is_streaming:507                auto_headers.append((b"transfer-encoding", b"chunked"))508            elif self.content:509                content_length = str(len(self.content)).encode()510                auto_headers.append((b"content-length", content_length))511        if not has_accept_encoding:512            auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))513514        for item in reversed(auto_headers):515            self.headers.raw.insert(0, item)516517    def __repr__(self) -> str:518        class_name = self.__class__.__name__519        url = str(self.url)520        return f"<{class_name}({self.method}, {url})>"521522523class Response:524    def __init__(525        self,526        status_code: int,527        *,528        reason_phrase: str = None,529        protocol: str = None,530        headers: HeaderTypes = None,531        content: ByteOrByteStream = b"",532        on_close: typing.Callable = None,533        request: Request = None,534        history: typing.List["Response"] = None,535    ):536        try:537            # Use a StatusCode IntEnum if possible, for a nicer representation.538            self.status_code = codes(status_code)  # type: int539        except ValueError:540            self.status_code = status_code541        self.reason_phrase = reason_phrase or get_reason_phrase(status_code)542        self.protocol = protocol543        self.headers = Headers(headers)544545        if isinstance(content, bytes):546            self.is_closed = True547            self.is_stream_consumed = True548            self._raw_content = content549        else:550            self.is_closed = False551            self.is_stream_consumed = False552            self._raw_stream = content553554        self.on_close = on_close555        self.request = request556        self.history = [] if history is None else list(history)557        self.next = None  # typing.Optional[typing.Callable]558559    @property560    def url(self) -> typing.Optional[URL]:561        """562        Returns the URL for which the request was made.563564        Requires that `request` was provided when instantiating the response.565        """566        return None if self.request is None else self.request.url567568    @property569    def content(self) -> bytes:570        if not hasattr(self, "_content"):571            if hasattr(self, "_raw_content"):572                content = self.decoder.decode(self._raw_content)573                content += self.decoder.flush()574                self._content = content575            else:576                raise ResponseNotRead()577        return self._content578579    @property580    def text(self) -> str:581        if not hasattr(self, "_text"):582            content = self.content583            if not content:584                self._text = ""585            else:586                encoding = self.encoding587                self._text = content.decode(encoding, errors="replace")588        return self._text589590    @property591    def encoding(self) -> str:592        if not hasattr(self, "_encoding"):593            encoding = self.charset_encoding594            if encoding is None or not is_known_encoding(encoding):595                encoding = self.apparent_encoding596                if encoding is None or not is_known_encoding(encoding):597                    encoding = "utf-8"598            self._encoding = encoding599        return self._encoding600601    @encoding.setter602    def encoding(self, value: str) -> None:603        self._encoding = value604605    @property606    def charset_encoding(self) -> typing.Optional[str]:607        """608        Return the encoding, as specified by the Content-Type header.609        """610        content_type = self.headers.get("Content-Type")611        if content_type is None:612            return None613614        parsed = cgi.parse_header(content_type)615        media_type, params = parsed[0], parsed[-1]616        if "charset" in params:617            return params["charset"].strip("'\"")618619        # RFC 2616 specifies that 'iso-8859-1' should be used as the default620        # for 'text/*' media types, if no charset is provided.621        # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1622        if media_type.startswith("text/"):623            return "iso-8859-1"624625        return None626627    @property628    def apparent_encoding(self) -> typing.Optional[str]:629        """630        Return the encoding, as it appears to autodetection.631        """632        return chardet.detect(self.content)["encoding"]633634    @property635    def decoder(self) -> Decoder:636        """637        Returns a decoder instance which can be used to decode the raw byte638        content, depending on the Content-Encoding used in the response.639        """640        if not hasattr(self, "_decoder"):641            decoders = []  # type: typing.List[Decoder]642            values = self.headers.getlist("content-encoding", split_commas=True)643            for value in values:644                value = value.strip().lower()645                decoder_cls = SUPPORTED_DECODERS[value]646                decoders.append(decoder_cls())647648            if len(decoders) == 1:649                self._decoder = decoders[0]650            elif len(decoders) > 1:651                self._decoder = MultiDecoder(decoders)652            else:653                self._decoder = IdentityDecoder()654655        return self._decoder656657    async def read(self) -> bytes:658        """659        Read and return the response content.660        """661        if not hasattr(self, "_content"):662            content = b""663            async for part in self.stream():664                content += part665            self._content = content666        return self._content667668    async def stream(self) -> typing.AsyncIterator[bytes]:669        """670        A byte-iterator over the decoded response content.671        This allows us to handle gzip, deflate, and brotli encoded responses.672        """673        if hasattr(self, "_content"):674            yield self._content675        else:676            async for chunk in self.raw():677                yield self.decoder.decode(chunk)678            yield self.decoder.flush()679680    async def raw(self) -> typing.AsyncIterator[bytes]:681        """682        A byte-iterator over the raw response content.683        """684        if hasattr(self, "_raw_content"):685            yield self._raw_content686        else:687            if self.is_stream_consumed:688                raise StreamConsumed()689            if self.is_closed:690                raise ResponseClosed()691692            self.is_stream_consumed = True693            async for part in self._raw_stream:694                yield part695            await self.close()696697    async def close(self) -> None:698        """699        Close the response and release the connection.700        Automatically called if the response body is read to completion.701        """702        if not self.is_closed:703            self.is_closed = True704            if self.on_close is not None:705                await self.on_close()706707    @property708    def is_redirect(self) -> bool:709        return (710            self.status_code711            in (712                codes.moved_permanently,713                codes.found,714                codes.see_other,715                codes.temporary_redirect,716                codes.permanent_redirect,717            )718            and "location" in self.headers719        )720721    def __repr__(self) -> str:722        class_name = self.__class__.__name__723        return f"<{class_name}(status_code={self.status_code})>"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)