Skip to content
Myr

models.py

This file

Path

httpcore/models.py

580 lines · 17.8 KiB · Python

Last changed by

Use rfc3986 for URL handlingTom Christiebefore adoption302fe93

History of this file

Take it

1import cgi2import typing34import chardet5import rfc398667from .config import SSLConfig, TimeoutConfig8from .decoders import (9    ACCEPT_ENCODING,10    SUPPORTED_DECODERS,11    Decoder,12    IdentityDecoder,13    MultiDecoder,14)15from .exceptions import InvalidURL, ResponseClosed, ResponseNotRead, StreamConsumed16from .status_codes import codes17from .utils import (18    get_reason_phrase,19    is_known_encoding,20    normalize_header_key,21    normalize_header_value,22)2324URLTypes = typing.Union["URL", str]2526HeaderTypes = typing.Union[27    "Headers",28    typing.Dict[typing.AnyStr, typing.AnyStr],29    typing.List[typing.Tuple[typing.AnyStr, typing.AnyStr]],30]3132ByteOrByteStream = typing.Union[bytes, typing.AsyncIterator[bytes]]333435class URL:36    def __init__(self, url: URLTypes, allow_relative: bool = False) -> None:37        if isinstance(url, str):38            self.components = rfc3986.api.uri_reference(url).normalize()39        elif isinstance(url, rfc3986.uri.URIReference):40            self.components = url41        else:42            self.components = url.components4344        if not allow_relative:45            if not self.scheme:46                raise InvalidURL("No scheme included in URL.")47            if self.scheme not in ("http", "https"):48                raise InvalidURL('URL scheme must be "http" or "https".')49            if not self.host:50                raise InvalidURL("No hostname included in URL.")5152    @property53    def scheme(self) -> str:54        return self.components.scheme or ""5556    @property57    def authority(self) -> str:58        return self.components.authority or ""5960    @property61    def path(self) -> str:62        return self.components.path or "/"6364    @property65    def query(self) -> str:66        return self.components.query or ""6768    @property69    def fragment(self) -> str:70        return self.components.fragment or ""7172    @property73    def host(self) -> str:74        return self.components.host or ""7576    @property77    def port(self) -> int:78        port = self.components.port79        if port is None:80            return {"https": 443, "http": 80}[self.scheme]81        return port8283    @property84    def full_path(self) -> str:85        path = self.path or "/"86        query = self.query87        if query:88            return path + "?" + query89        return path9091    @property92    def is_secure(self) -> bool:93        return self.components.scheme == "https"9495    @property96    def is_absolute(self) -> bool:97        return self.components.is_absolute()9899    @property100    def origin(self) -> "Origin":101        return Origin(self)102103    def copy_with(self, **kwargs: typing.Any) -> "URL":104        return URL(self.components.copy_with(**kwargs))105106    def resolve_with(self, base_url: URLTypes) -> "URL":107        if isinstance(base_url, URL):108            base_url = base_url.components109        return URL(self.components.resolve_with(base_url))110111    def __hash__(self) -> int:112        return hash(str(self))113114    def __eq__(self, other: typing.Any) -> bool:115        return isinstance(other, URL) and str(self) == str(other)116117    def __str__(self) -> str:118        return self.components.unsplit()119120    def __repr__(self) -> str:121        class_name = self.__class__.__name__122        url_str = str(self)123        return f"{class_name}({url_str!r})"124125126class Origin:127    def __init__(self, url: URLTypes) -> None:128        if not isinstance(url, URL):129            url = URL(url)130        self.is_ssl = url.scheme == "https"131        self.host = url.host132        self.port = url.port133134    def __eq__(self, other: typing.Any) -> bool:135        return (136            isinstance(other, self.__class__)137            and self.is_ssl == other.is_ssl138            and self.host == other.host139            and self.port == other.port140        )141142    def __hash__(self) -> int:143        return hash((self.is_ssl, self.host, self.port))144145146class Headers(typing.MutableMapping[str, str]):147    """148    A case-insensitive multidict.149    """150151    def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:152        if headers is None:153            self._list = []  # type: typing.List[typing.Tuple[bytes, bytes]]154        elif isinstance(headers, Headers):155            self._list = list(headers.raw)156        elif isinstance(headers, dict):157            self._list = [158                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))159                for k, v in headers.items()160            ]161        else:162            self._list = [163                (normalize_header_key(k, encoding), normalize_header_value(v, encoding))164                for k, v in headers165            ]166        self._encoding = encoding167168    @property169    def encoding(self) -> str:170        """171        Header encoding is mandated as ascii, but utf-8 or iso-8859-1 may be172        seen in the wild.173        """174        if self._encoding is None:175            for encoding in ["ascii", "utf-8"]:176                for key, value in self.raw:177                    try:178                        key.decode(encoding)179                        value.decode(encoding)180                    except UnicodeDecodeError:181                        break182                else:183                    # The else block runs if 'break' did not occur, meaning184                    # all values fitted the encoding.185                    self._encoding = encoding186                    break187            else:188                # The ISO-8859-1 encoding covers all 256 code points in a byte,189                # so will never raise decode errors.190                self._encoding = "iso-8859-1"191        return self._encoding192193    @encoding.setter194    def encoding(self, value: str) -> None:195        self._encoding = value196197    @property198    def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:199        """200        Returns a list of the raw header items, as byte pairs.201        May be mutated in-place.202        """203        return self._list204205    def keys(self) -> typing.List[str]:  # type: ignore206        return [key.decode(self.encoding) for key, value in self._list]207208    def values(self) -> typing.List[str]:  # type: ignore209        return [value.decode(self.encoding) for key, value in self._list]210211    def items(self) -> typing.List[typing.Tuple[str, str]]:  # type: ignore212        return [213            (key.decode(self.encoding), value.decode(self.encoding))214            for key, value in self._list215        ]216217    def get(self, key: str, default: typing.Any = None) -> typing.Any:218        try:219            return self[key]220        except KeyError:221            return default222223    def getlist(self, key: str, split_commas: bool = False) -> typing.List[str]:224        """225        Return multiple header values.226        """227        get_header_key = key.lower().encode(self.encoding)228229        values = [230            item_value.decode(self.encoding)231            for item_key, item_value in self._list232            if item_key == get_header_key233        ]234235        if not split_commas:236            return values237238        split_values = []239        for value in values:240            split_values.extend([item.strip() for item in value.split(",")])241        return split_values242243    def __getitem__(self, key: str) -> str:244        """245        Return a single header value.246247        If there are multiple headers with the same key, then we concatenate248        them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2249        """250        normalized_key = key.lower().encode(self.encoding)251252        items = []253        for header_key, header_value in self._list:254            if header_key == normalized_key:255                items.append(header_value.decode(self.encoding))256257        if items:258            return ", ".join(items)259260        raise KeyError(key)261262    def __setitem__(self, key: str, value: str) -> None:263        """264        Set the header `key` to `value`, removing any duplicate entries.265        Retains insertion order.266        """267        set_key = key.lower().encode(self.encoding)268        set_value = value.encode(self.encoding)269270        found_indexes = []271        for idx, (item_key, item_value) in enumerate(self._list):272            if item_key == set_key:273                found_indexes.append(idx)274275        for idx in reversed(found_indexes[1:]):276            del self._list[idx]277278        if found_indexes:279            idx = found_indexes[0]280            self._list[idx] = (set_key, set_value)281        else:282            self._list.append((set_key, set_value))283284    def __delitem__(self, key: str) -> None:285        """286        Remove the header `key`.287        """288        del_key = key.lower().encode(self.encoding)289290        pop_indexes = []291        for idx, (item_key, item_value) in enumerate(self._list):292            if item_key == del_key:293                pop_indexes.append(idx)294295        for idx in reversed(pop_indexes):296            del self._list[idx]297298    def __contains__(self, key: typing.Any) -> bool:299        get_header_key = key.lower().encode(self.encoding)300        for header_key, header_value in self._list:301            if header_key == get_header_key:302                return True303        return False304305    def __iter__(self) -> typing.Iterator[typing.Any]:306        return iter(self.keys())307308    def __len__(self) -> int:309        return len(self._list)310311    def __eq__(self, other: typing.Any) -> bool:312        if not isinstance(other, Headers):313            return False314        return sorted(self._list) == sorted(other._list)315316    def __repr__(self) -> str:317        class_name = self.__class__.__name__318319        encoding_str = ""320        if self.encoding != "ascii":321            encoding_str = f", encoding={self.encoding!r}"322323        as_dict = dict(self.items())324        if len(as_dict) == len(self):325            return f"{class_name}({as_dict!r}{encoding_str})"326        as_list = self.items()327        return f"{class_name}({as_list!r}{encoding_str})"328329330class Request:331    def __init__(332        self,333        method: str,334        url: typing.Union[str, URL],335        *,336        headers: HeaderTypes = None,337        content: ByteOrByteStream = b"",338    ):339        self.method = method.upper()340        self.url = URL(url) if isinstance(url, str) else url341        if isinstance(content, bytes):342            self.is_streaming = False343            self.content = content344        else:345            self.is_streaming = True346            self.content_aiter = content347        self.headers = Headers(headers)348349    async def read(self) -> bytes:350        """351        Read and return the response content.352        """353        if not hasattr(self, "content"):354            content = b""355            async for part in self.stream():356                content += part357            self.content = content358        return self.content359360    async def stream(self) -> typing.AsyncIterator[bytes]:361        if self.is_streaming:362            async for part in self.content_aiter:363                yield part364        elif self.content:365            yield self.content366367    def prepare(self) -> None:368        """369        Adds in any default headers. When using the `Client`, this will370        end up being called into by the `prepare_request()` stage.371372        You can omit this behavior by calling `Client.send()` with an373        explicitly built `Request` instance.374        """375        auto_headers = []  # type: typing.List[typing.Tuple[bytes, bytes]]376377        has_host = "host" in self.headers378        has_content_length = (379            "content-length" in self.headers or "transfer-encoding" in self.headers380        )381        has_accept_encoding = "accept-encoding" in self.headers382383        if not has_host and self.url.authority:384            auto_headers.append((b"host", self.url.authority.encode("ascii")))385        if not has_content_length:386            if self.is_streaming:387                auto_headers.append((b"transfer-encoding", b"chunked"))388            elif self.content:389                content_length = str(len(self.content)).encode()390                auto_headers.append((b"content-length", content_length))391        if not has_accept_encoding:392            auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))393394        for item in reversed(auto_headers):395            self.headers.raw.insert(0, item)396397398class Response:399    def __init__(400        self,401        status_code: int,402        *,403        reason_phrase: str = None,404        protocol: str = None,405        headers: HeaderTypes = None,406        content: ByteOrByteStream = b"",407        on_close: typing.Callable = None,408        request: Request = None,409        history: typing.List["Response"] = None,410    ):411        self.status_code = status_code412        self.reason_phrase = reason_phrase or get_reason_phrase(status_code)413        self.protocol = protocol414        self.headers = Headers(headers)415416        if isinstance(content, bytes):417            self.is_closed = True418            self.is_stream_consumed = True419            self._raw_content = content420        else:421            self.is_closed = False422            self.is_stream_consumed = False423            self._raw_stream = content424425        self.on_close = on_close426        self.request = request427        self.history = [] if history is None else list(history)428        self.next = None  # typing.Optional[typing.Callable]429430    @property431    def url(self) -> typing.Optional[URL]:432        """433        Returns the URL for which the request was made.434435        Requires that `request` was provided when instantiating the response.436        """437        return None if self.request is None else self.request.url438439    @property440    def content(self) -> bytes:441        if not hasattr(self, "_content"):442            if hasattr(self, "_raw_content"):443                content = self.decoder.decode(self._raw_content)444                content += self.decoder.flush()445                self._content = content446            else:447                raise ResponseNotRead()448        return self._content449450    @property451    def text(self) -> str:452        if not hasattr(self, "_text"):453            content = self.content454            if not content:455                self._text = ""456            else:457                encoding = self.encoding458                self._text = content.decode(encoding, errors="replace")459        return self._text460461    @property462    def encoding(self) -> str:463        if not hasattr(self, "_encoding"):464            encoding = self.charset_encoding465            if encoding is None or not is_known_encoding(encoding):466                encoding = self.apparent_encoding467                if encoding is None or not is_known_encoding(encoding):468                    encoding = "utf-8"469            self._encoding = encoding470        return self._encoding471472    @encoding.setter473    def encoding(self, value: str) -> None:474        self._encoding = value475476    @property477    def charset_encoding(self) -> typing.Optional[str]:478        """479        Return the encoding, as specified by the Content-Type header.480        """481        content_type = self.headers.get("Content-Type")482        if content_type is None:483            return None484485        parsed = cgi.parse_header(content_type)[-1]486        return parsed.get("charset")487488    @property489    def apparent_encoding(self) -> typing.Optional[str]:490        """491        Return the encoding, as it appears to autodetection.492        """493        return chardet.detect(self.content)["encoding"]494495    @property496    def decoder(self) -> Decoder:497        """498        Returns a decoder instance which can be used to decode the raw byte499        content, depending on the Content-Encoding used in the response.500        """501        if not hasattr(self, "_decoder"):502            decoders = []  # type: typing.List[Decoder]503            values = self.headers.getlist("content-encoding", split_commas=True)504            for value in values:505                value = value.strip().lower()506                decoder_cls = SUPPORTED_DECODERS[value]507                decoders.append(decoder_cls())508509            if len(decoders) == 1:510                self._decoder = decoders[0]511            elif len(decoders) > 1:512                self._decoder = MultiDecoder(decoders)513            else:514                self._decoder = IdentityDecoder()515516        return self._decoder517518    async def read(self) -> bytes:519        """520        Read and return the response content.521        """522        if not hasattr(self, "_content"):523            content = b""524            async for part in self.stream():525                content += part526            self._content = content527        return self._content528529    async def stream(self) -> typing.AsyncIterator[bytes]:530        """531        A byte-iterator over the decoded response content.532        This allows us to handle gzip, deflate, and brotli encoded responses.533        """534        if hasattr(self, "_content"):535            yield self._content536        else:537            async for chunk in self.raw():538                yield self.decoder.decode(chunk)539            yield self.decoder.flush()540541    async def raw(self) -> typing.AsyncIterator[bytes]:542        """543        A byte-iterator over the raw response content.544        """545        if hasattr(self, "_raw_content"):546            yield self._raw_content547        else:548            if self.is_stream_consumed:549                raise StreamConsumed()550            if self.is_closed:551                raise ResponseClosed()552553            self.is_stream_consumed = True554            async for part in self._raw_stream:555                yield part556            await self.close()557558    async def close(self) -> None:559        """560        Close the response and release the connection.561        Automatically called if the response body is read to completion.562        """563        if not self.is_closed:564            self.is_closed = True565            if self.on_close is not None:566                await self.on_close()567568    @property569    def is_redirect(self) -> bool:570        return (571            self.status_code572            in (573                codes.moved_permanently,574                codes.found,575                codes.see_other,576                codes.temporary_redirect,577                codes.permanent_redirect,578            )579            and "location" in self.headers580        )