Skip to content
Myr

models.py

This file

Path

httpcore/models.py

824 lines · 25.3 KiB · Python

Last changed by

Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369

History of this file

Take it

1import asyncio2import cgi3import typing4from urllib.parse import parse_qsl, urlencode56import chardet7import idna8import rfc3986910from .config import SSLConfig, TimeoutConfig11from .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 .status_codes import codes26from .utils import (27    get_reason_phrase,28    is_known_encoding,29    normalize_header_key,30    normalize_header_value,31)3233URLTypes = typing.Union["URL", str]3435QueryParamTypes = typing.Union[36    "QueryParams",37    typing.Mapping[str, str],38    typing.List[typing.Tuple[typing.Any, typing.Any]],39    str,40]4142HeaderTypes = typing.Union[43    "Headers",44    typing.Dict[typing.AnyStr, typing.AnyStr],45    typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],46]4748RequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]4950ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]515253class URL:54    def __init__(55        self,56        url: URLTypes,57        allow_relative: bool = False,58        query_params: QueryParamTypes = None,59    ) -> None:60        if isinstance(url, rfc3986.uri.URIReference):61            self.components = url62        elif isinstance(url, str):63            self.components = rfc3986.api.uri_reference(url)64        else:65            self.components = url.components6667        # Handle IDNA domain names.68        if self.components.authority:69            idna_authority = self.components.authority.encode("idna").decode("ascii")70            if idna_authority != self.components.authority:71                self.components = self.components.copy_with(authority=idna_authority)7273        # Normalize scheme and domain name.74        self.components = self.components.normalize()7576        # Add any query parameters.77        if query_params:78            query_string = str(QueryParams(query_params))79            self.components = self.components.copy_with(query=query_string)8081        # Enforce absolute URLs by default.82        if not allow_relative:83            if not self.scheme:84                raise InvalidURL("No scheme included in URL.")85            if self.scheme not in ("http", "https"):86                raise InvalidURL('URL scheme must be "http" or "https".')87            if not self.host:88                raise InvalidURL("No host included in URL.")8990    @property91    def scheme(self) -> str:92        return self.components.scheme or ""9394    @property95    def authority(self) -> str:96        return self.components.authority or ""9798    @property99    def host(self) -> str:100        return self.components.host or ""101102    @property103    def port(self) -> int:104        port = self.components.port105        if port is None:106            return {"https": 443, "http": 80}[self.scheme]107        return int(port)108109    @property110    def path(self) -> str:111        return self.components.path or "/"112113    @property114    def query(self) -> str:115        return self.components.query or ""116117    @property118    def full_path(self) -> str:119        path = self.path120        if self.query:121            path += "?" + self.query122        return path123124    @property125    def fragment(self) -> str:126        return self.components.fragment or ""127128    @property129    def is_ssl(self) -> bool:130        return self.components.scheme == "https"131132    @property133    def is_absolute_url(self) -> bool:134        """135        Return `True` for absolute URLs such as 'http://example.com/path',136        and `False` for relative URLs such as '/path'.137        """138        # We don't use rfc3986's `is_absolute` because it treats139        # URLs with a fragment portion as not absolute.140        # What we actually care about is if the URL provides141        # a scheme and hostname to which connections should be made.142        return self.components.scheme and self.components.host143144    @property145    def is_relative_url(self) -> bool:146        return not self.is_absolute_url147148    @property149    def origin(self) -> "Origin":150        return Origin(self)151152    def copy_with(self, **kwargs: typing.Any) -> "URL":153        return URL(self.components.copy_with(**kwargs))154155    def resolve_with(self, base_url: URLTypes) -> "URL":156        """157        Return an absolute URL, using base_url as the base.158        """159        # We drop any fragment portion, because RFC 3986 strictly160        # treats URLs with a fragment portion as not being absolute URLs.161        base_url = URL(base_url).copy_with(fragment=None)162        return URL(self.components.resolve_with(base_url.components))163164    def __hash__(self) -> int:165        return hash(str(self))166167    def __eq__(self, other: typing.Any) -> bool:168        return isinstance(other, URL) and str(self) == str(other)169170    def __str__(self) -> str:171        return self.components.unsplit()172173    def __repr__(self) -> str:174        class_name = self.__class__.__name__175        url_str = str(self)176        return f"{class_name}({url_str!r})"177178179class Origin:180    """181    The URL scheme and authority information, as a comparable, hashable object.182    """183184    def __init__(self, url: URLTypes) -> None:185        if not isinstance(url, URL):186            url = URL(url)187        self.is_ssl = url.is_ssl188        self.host = url.host189        self.port = url.port190191    def __eq__(self, other: typing.Any) -> bool:192        return (193            isinstance(other, self.__class__)194            and self.is_ssl == other.is_ssl195            and self.host == other.host196            and self.port == other.port197        )198199    def __hash__(self) -> int:200        return hash((self.is_ssl, self.host, self.port))201202203class QueryParams(typing.Mapping[str, str]):204    """205    URL query parameters, as a multi-dict.206    """207208    def __init__(self, *args: QueryParamTypes, **kwargs: typing.Any) -> None:209        assert len(args) < 2, "Too many arguments."210        assert not (args and kwargs), "Cannot mix named and unnamed arguments."211212        value = args[0] if args else kwargs213214        if isinstance(value, str):215            items = parse_qsl(value)216        elif isinstance(value, QueryParams):217            items = value.multi_items()218        elif isinstance(value, list):219            items = value220        else:221            items = value.items()  # type: ignore222223        self._list = [(str(k), str(v)) for k, v in items]224        self._dict = {str(k): str(v) for k, v in items}225226    def getlist(self, key: typing.Any) -> typing.List[str]:227        return [item_value for item_key, item_value in self._list if item_key == key]228229    def keys(self) -> typing.KeysView:230        return self._dict.keys()231232    def values(self) -> typing.ValuesView:233        return self._dict.values()234235    def items(self) -> typing.ItemsView:236        return self._dict.items()237238    def multi_items(self) -> typing.List[typing.Tuple[str, str]]:239        return list(self._list)240241    def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:242        if key in self._dict:243            return self._dict[key]244        return default245246    def __getitem__(self, key: typing.Any) -> str:247        return self._dict[key]248249    def __contains__(self, key: typing.Any) -> bool:250        return key in self._dict251252    def __iter__(self) -> typing.Iterator[typing.Any]:253        return iter(self.keys())254255    def __len__(self) -> int:256        return len(self._dict)257258    def __eq__(self, other: typing.Any) -> bool:259        if not isinstance(other, self.__class__):260            return False261        return sorted(self._list) == sorted(other._list)262263    def __str__(self) -> str:264        return urlencode(self._list)265266    def __repr__(self) -> str:267        class_name = self.__class__.__name__268        query_string = str(self)269        return f"{class_name}({query_string!r})"270271272class Headers(typing.MutableMapping[str, str]):273    """274    HTTP headers, as a case-insensitive multi-dict.275    """276277    def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:278        if headers is None:279            self._list = []  # type: typing.List[typing.Tuple[bytes, bytes]]280        elif isinstance(headers, Headers):281            self._list = list(headers.raw)282        elif isinstance(headers, dict):283            self._list = [284                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))285                for k, v in headers.items()286            ]287        else:288            self._list = [289                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))290                for k, v in headers291            ]292        self._encoding = encoding293294    @property295    def encoding(self) -> str:296        """297        Header encoding is mandated as ascii, but we allow fallbacks to utf-8298        or iso-8859-1.299        """300        if self._encoding is None:301            for encoding in ["ascii", "utf-8"]:302                for key, value in self.raw:303                    try:304                        key.decode(encoding)305                        value.decode(encoding)306                    except UnicodeDecodeError:307                        break308                else:309                    # The else block runs if 'break' did not occur, meaning310                    # all values fitted the encoding.311                    self._encoding = encoding312                    break313            else:314                # The ISO-8859-1 encoding covers all 256 code points in a byte,315                # so will never raise decode errors.316                self._encoding = "iso-8859-1"317        return self._encoding318319    @encoding.setter320    def encoding(self, value: str) -> None:321        self._encoding = value322323    @property324    def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:325        """326        Returns a list of the raw header items, as byte pairs.327        May be mutated in-place.328        """329        return self._list330331    def keys(self) -> typing.List[str]:  # type: ignore332        return [key.decode(self.encoding) for key, value in self._list]333334    def values(self) -> typing.List[str]:  # type: ignore335        return [value.decode(self.encoding) for key, value in self._list]336337    def items(self) -> typing.List[typing.Tuple[str, str]]:  # type: ignore338        return [339            (key.decode(self.encoding), value.decode(self.encoding))340            for key, value in self._list341        ]342343    def get(self, key: str, default: typing.Any = None) -> typing.Any:344        try:345            return self[key]346        except KeyError:347            return default348349    def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:350        """351        Return multiple header values.352        """353        get_header_key = key.lower().encode(self.encoding)354355        values = [356            item_value.decode(self.encoding)357            for item_key, item_value in self._list358            if item_key == get_header_key359        ]360361        if not split_commas:362            return values363364        split_values = []365        for value in values:366            split_values.extend([item.strip() for item in value.split(",")])367        return split_values368369    def __getitem__(self, key: str) -> str:370        """371        Return a single header value.372373        If there are multiple headers with the same key, then we concatenate374        them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2375        """376        normalized_key = key.lower().encode(self.encoding)377378        items = []379        for header_key, header_value in self._list:380            if header_key == normalized_key:381                items.append(header_value.decode(self.encoding))382383        if items:384            return ", ".join(items)385386        raise KeyError(key)387388    def __setitem__(self, key: str, value: str) -> None:389        """390        Set the header `key` to `value`, removing any duplicate entries.391        Retains insertion order.392        """393        set_key = key.lower().encode(self.encoding)394        set_value = value.encode(self.encoding)395396        found_indexes = []397        for idx, (item_key, item_value) in enumerate(self._list):398            if item_key == set_key:399                found_indexes.append(idx)400401        for idx in reversed(found_indexes[1:]):402            del self._list[idx]403404        if found_indexes:405            idx = found_indexes[0]406            self._list[idx] = (set_key, set_value)407        else:408            self._list.append((set_key, set_value))409410    def __delitem__(self, key: str) -> None:411        """412        Remove the header `key`.413        """414        del_key = key.lower().encode(self.encoding)415416        pop_indexes = []417        for idx, (item_key, item_value) in enumerate(self._list):418            if item_key == del_key:419                pop_indexes.append(idx)420421        for idx in reversed(pop_indexes):422            del self._list[idx]423424    def __contains__(self, key: typing.Any) -> bool:425        get_header_key = key.lower().encode(self.encoding)426        for header_key, header_value in self._list:427            if header_key == get_header_key:428                return True429        return False430431    def __iter__(self) -> typing.Iterator[typing.Any]:432        return iter(self.keys())433434    def __len__(self) -> int:435        return len(self._list)436437    def __eq__(self, other: typing.Any) -> bool:438        if not isinstance(other, Headers):439            return False440        return sorted(self._list) == sorted(other._list)441442    def __repr__(self) -> str:443        class_name = self.__class__.__name__444445        encoding_str = ""446        if self.encoding != "ascii":447            encoding_str = f", encoding={self.encoding!r}"448449        as_dict = dict(self.items())450        if len(as_dict) == len(self):451            return f"{class_name}({as_dict!r}{encoding_str})"452        as_list = self.items()453        return f"{class_name}({as_list!r}{encoding_str})"454455456class Request:457    def __init__(458        self,459        method: str,460        url: typing.Union[str, URL],461        *,462        data: RequestData = b"",463        query_params: QueryParamTypes = None,464        headers: HeaderTypes = None,465    ):466        self.method = method.upper()467        self.url = URL(url, query_params=query_params)468        self.headers = Headers(headers)469470        if isinstance(data, bytes):471            self.is_streaming = False472            self.content = data473        elif isinstance(data, dict):474            self.is_streaming = False475            self.content = urlencode(data, doseq=True).encode("utf-8")476            self.headers["Content-Type"] = "application/x-www-form-urlencoded"477        else:478            self.is_streaming = True479            self.content_aiter = data480481    async def read(self) -> bytes:482        """483        Read and return the response content.484        """485        if not hasattr(self, "content"):486            self.content = b"".join([part async for part in self.stream()])487        return self.content488489    async def stream(self) -> typing.AsyncIterator[bytes]:490        if self.is_streaming:491            async for part in self.content_aiter:492                yield part493        elif self.content:494            yield self.content495496    def prepare(self) -> None:497        """498        Adds in any default headers. When using the `Client`, this will499        end up being called into by the `prepare_request()` stage.500501        You can omit this behavior by calling `Client.send()` with an502        explicitly built `Request` instance.503        """504        auto_headers = []  # type: typing.List[typing.Tuple[bytes, bytes]]505506        has_host = "host" in self.headers507        has_content_length = (508            "content-length" in self.headers or "transfer-encoding" in self.headers509        )510        has_accept_encoding = "accept-encoding" in self.headers511512        if not has_host and self.url.authority:513            auto_headers.append((b"host", self.url.authority.encode("ascii")))514        if not has_content_length:515            if self.is_streaming:516                auto_headers.append((b"transfer-encoding", b"chunked"))517            elif self.content:518                content_length = str(len(self.content)).encode()519                auto_headers.append((b"content-length", content_length))520        if not has_accept_encoding:521            auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))522523        for item in reversed(auto_headers):524            self.headers.raw.insert(0, item)525526    def __repr__(self) -> str:527        class_name = self.__class__.__name__528        url = str(self.url)529        return f"<{class_name}({self.method!r}, {url!r})>"530531532class Response:533    def __init__(534        self,535        status_code: int,536        *,537        reason_phrase: str = None,538        protocol: str = None,539        headers: HeaderTypes = None,540        content: ResponseContent = b"",541        on_close: typing.Callable = None,542        request: Request = None,543        history: typing.List["Response"] = None,544    ):545        try:546            # Use a StatusCode IntEnum if possible, for a nicer representation.547            self.status_code = codes(status_code)  # type: int548        except ValueError:549            self.status_code = status_code550        self.reason_phrase = reason_phrase or get_reason_phrase(status_code)551        self.protocol = protocol552        self.headers = Headers(headers)553554        if isinstance(content, bytes):555            self.is_closed = True556            self.is_stream_consumed = True557            self._raw_content = content558        else:559            self.is_closed = False560            self.is_stream_consumed = False561            self._raw_stream = content562563        self.on_close = on_close564        self.request = request565        self.history = [] if history is None else list(history)566        self.next = None  # typing.Optional[typing.Callable]567568    @property569    def url(self) -> typing.Optional[URL]:570        """571        Returns the URL for which the request was made.572573        Requires that `request` was provided when instantiating the response.574        """575        return None if self.request is None else self.request.url576577    @property578    def content(self) -> bytes:579        if not hasattr(self, "_content"):580            if hasattr(self, "_raw_content"):581                content = self.decoder.decode(self._raw_content)582                content += self.decoder.flush()583                self._content = content584            else:585                raise ResponseNotRead()586        return self._content587588    @property589    def text(self) -> str:590        if not hasattr(self, "_text"):591            content = self.content592            if not content:593                self._text = ""594            else:595                encoding = self.encoding596                self._text = content.decode(encoding, errors="replace")597        return self._text598599    @property600    def encoding(self) -> str:601        if not hasattr(self, "_encoding"):602            encoding = self.charset_encoding603            if encoding is None or not is_known_encoding(encoding):604                encoding = self.apparent_encoding605                if encoding is None or not is_known_encoding(encoding):606                    encoding = "utf-8"607            self._encoding = encoding608        return self._encoding609610    @encoding.setter611    def encoding(self, value: str) -> None:612        self._encoding = value613614    @property615    def charset_encoding(self) -> typing.Optional[str]:616        """617        Return the encoding, as specified by the Content-Type header.618        """619        content_type = self.headers.get("Content-Type")620        if content_type is None:621            return None622623        parsed = cgi.parse_header(content_type)624        media_type, params = parsed[0], parsed[-1]625        if "charset" in params:626            return params["charset"].strip("'\"")627628        # RFC 2616 specifies that 'iso-8859-1' should be used as the default629        # for 'text/*' media types, if no charset is provided.630        # See: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1631        if media_type.startswith("text/"):632            return "iso-8859-1"633634        return None635636    @property637    def apparent_encoding(self) -> typing.Optional[str]:638        """639        Return the encoding, as it appears to autodetection.640        """641        return chardet.detect(self.content)["encoding"]642643    @property644    def decoder(self) -> Decoder:645        """646        Returns a decoder instance which can be used to decode the raw byte647        content, depending on the Content-Encoding used in the response.648        """649        if not hasattr(self, "_decoder"):650            decoders = []  # type: typing.List[Decoder]651            values = self.headers.getlist("content-encoding", split_commas=True)652            for value in values:653                value = value.strip().lower()654                decoder_cls = SUPPORTED_DECODERS[value]655                decoders.append(decoder_cls())656657            if len(decoders) == 1:658                self._decoder = decoders[0]659            elif len(decoders) > 1:660                self._decoder = MultiDecoder(decoders)661            else:662                self._decoder = IdentityDecoder()663664        return self._decoder665666    async def read(self) -> bytes:667        """668        Read and return the response content.669        """670        if not hasattr(self, "_content"):671            self._content = b"".join([part async for part in self.stream()])672        return self._content673674    async def stream(self) -> typing.AsyncIterator[bytes]:675        """676        A byte-iterator over the decoded response content.677        This allows us to handle gzip, deflate, and brotli encoded responses.678        """679        if hasattr(self, "_content"):680            yield self._content681        else:682            async for chunk in self.raw():683                yield self.decoder.decode(chunk)684            yield self.decoder.flush()685686    async def raw(self) -> typing.AsyncIterator[bytes]:687        """688        A byte-iterator over the raw response content.689        """690        if hasattr(self, "_raw_content"):691            yield self._raw_content692        else:693            if self.is_stream_consumed:694                raise StreamConsumed()695            if self.is_closed:696                raise ResponseClosed()697698            self.is_stream_consumed = True699            async for part in self._raw_stream:700                yield part701            await self.close()702703    async def close(self) -> None:704        """705        Close the response and release the connection.706        Automatically called if the response body is read to completion.707        """708        if not self.is_closed:709            self.is_closed = True710            if self.on_close is not None:711                await self.on_close()712713    @property714    def is_redirect(self) -> bool:715        return (716            self.status_code717            in (718                codes.MOVED_PERMANENTLY,719                codes.FOUND,720                codes.SEE_OTHER,721                codes.TEMPORARY_REDIRECT,722                codes.PERMANENT_REDIRECT,723            )724            and "location" in self.headers725        )726727    def raise_for_status(self) -> None:728        """729        Raise the `HttpError` if one occurred.730        """731        message = (732            "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"733            "For more information check: https://httpstatuses.com/{0.status_code}"734        )735736        if 400 <= self.status_code < 500:737            message = message.format(self, error_type="Client Error")738        elif 500 <= self.status_code < 600:739            message = message.format(self, error_type="Server Error")740        else:741            message = ""742743        if message:744            raise HttpError(message)745746    def __repr__(self) -> str:747        class_name = self.__class__.__name__748        return f"<{class_name}({self.status_code}, {self.reason_phrase!r})>"749750751class SyncResponse:752    """753    A thread-synchronous response. This class proxies onto a `Response`754    instance, providing standard synchronous interfaces where required.755    """756757    def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):758        self._response = response759        self._loop = loop760761    @property762    def status_code(self) -> int:763        return self._response.status_code764765    @property766    def reason_phrase(self) -> str:767        return self._response.reason_phrase768769    @property770    def protocol(self) -> typing.Optional[str]:771        return self._response.protocol772773    @property774    def url(self) -> typing.Optional[URL]:775        return self._response.url776777    @property778    def request(self) -> typing.Optional[Request]:779        return self._response.request780781    @property782    def headers(self) -> Headers:783        return self._response.headers784785    @property786    def content(self) -> bytes:787        return self._response.content788789    @property790    def text(self) -> str:791        return self._response.text792793    @property794    def encoding(self) -> str:795        return self._response.encoding796797    @property798    def is_redirect(self) -> bool:799        return self._response.is_redirect800801    def raise_for_status(self) -> None:802        return self._response.raise_for_status()803804    def read(self) -> bytes:805        return self._loop.run_until_complete(self._response.read())806807    def stream(self) -> typing.Iterator[bytes]:808        inner = self._response.stream()809        while True:810            try:811                yield self._loop.run_until_complete(inner.__anext__())812            except StopAsyncIteration as exc:813                break814815    def raw(self) -> typing.Iterator[bytes]:816        inner = self._response.raw()817        while True:818            try:819                yield self._loop.run_until_complete(inner.__anext__())820            except StopAsyncIteration as exc:821                break822823    def close(self) -> None:824        return self._loop.run_until_complete(self._response.close())