Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
__init__.py220 linesDownload Raw Back to requests
1#   __2#  /__)  _  _     _   _ _/   _3# / (   (- (/ (/ (- _)  /  _)4#          /5 6"""7Requests HTTP Library8~~~~~~~~~~~~~~~~~~~~~9 10Requests is an HTTP library, written in Python, for human beings.11Basic GET usage:12 13   >>> import requests14   >>> r = requests.get('https://www.python.org')15   >>> r.status_code16   20017   >>> b'Python is a programming language' in r.content18   True19 20... or POST:21 22   >>> payload = dict(key1='value1', key2='value2')23   >>> r = requests.post('https://httpbin.org/post', data=payload)24   >>> print(r.text)25   {26     ...27     "form": {28       "key1": "value1",29       "key2": "value2"30     },31     ...32   }33 34The other HTTP methods are supported - see `requests.api`. Full documentation35is at <https://requests.readthedocs.io>.36 37:copyright: (c) 2017 by Kenneth Reitz.38:license: Apache 2.0, see LICENSE for more details.39"""40 41from __future__ import annotations42 43import warnings44 45import urllib346 47from .exceptions import RequestsDependencyWarning48 49try:50    from charset_normalizer import __version__ as charset_normalizer_version51except ImportError:52    charset_normalizer_version = None53 54try:55    from chardet import __version__ as chardet_version  # type: ignore[import-not-found]56except ImportError:57    chardet_version = None58 59 60def check_compatibility(61    urllib3_version: str,62    chardet_version: str | None,63    charset_normalizer_version: str | None,64) -> None:65    urllib3_version_list = urllib3_version.split(".")[:3]66    assert urllib3_version_list != ["dev"]  # Verify urllib3 isn't installed from git.67 68    # Sometimes, urllib3 only reports its version as 16.1.69    if len(urllib3_version_list) == 2:70        urllib3_version_list.append("0")71 72    # Check urllib3 for compatibility.73    major, minor, patch = urllib3_version_list  # noqa: F81174    major, minor, patch = int(major), int(minor), int(patch)75    # urllib3 >= 1.21.176    assert major >= 177    if major == 1:78        assert minor >= 2179 80    # Check charset_normalizer for compatibility.81    if chardet_version:82        major, minor, patch = chardet_version.split(".")[:3]83        major, minor, patch = int(major), int(minor), int(patch)84        # chardet_version >= 3.0.2, < 8.0.085        assert (3, 0, 2) <= (major, minor, patch) < (8, 0, 0)86    elif charset_normalizer_version:87        major, minor, patch = charset_normalizer_version.split(".")[:3]88        major, minor, patch = int(major), int(minor), int(patch)89        # charset_normalizer >= 2.0.0 < 4.0.090        assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0)91    else:92        warnings.warn(93            "Unable to find acceptable character detection dependency "94            "(chardet or charset_normalizer).",95            RequestsDependencyWarning,96        )97 98 99def _check_cryptography(cryptography_version: str) -> None:100    # cryptography < 1.3.4101    try:102        cryptography_version_list = list(map(int, cryptography_version.split(".")))103    except ValueError:104        return105 106    if cryptography_version_list < [1, 3, 4]:107        warning = f"Old version of cryptography ({cryptography_version_list}) may cause slowdown."108        warnings.warn(warning, RequestsDependencyWarning)109 110 111# Check imported dependencies for compatibility.112try:113    check_compatibility(114        urllib3.__version__,  # type: ignore[reportPrivateImportUsage]115        chardet_version,  # type: ignore[reportUnknownArgumentType]116        charset_normalizer_version,117    )118except (AssertionError, ValueError):119    warnings.warn(120        f"urllib3 ({urllib3.__version__}) or chardet "  # type: ignore[reportPrivateImportUsage]121        f"({chardet_version})/charset_normalizer ({charset_normalizer_version}) "122        "doesn't match a supported version!",123        RequestsDependencyWarning,124    )125 126# Attempt to enable urllib3's fallback for SNI support127# if the standard library doesn't support SNI or the128# 'ssl' library isn't available.129try:130    try:131        import ssl132    except ImportError:133        ssl = None134 135    if not getattr(ssl, "HAS_SNI", False):136        from urllib3.contrib import pyopenssl137 138        pyopenssl.inject_into_urllib3()139 140        # Check cryptography version141        from cryptography import (  # type: ignore[reportMissingImports]142            __version__ as cryptography_version,  # type: ignore[reportUnknownVariableType]143        )144 145        _check_cryptography(cryptography_version)  # type: ignore[reportUnknownArgumentType]146except ImportError:147    pass148 149# urllib3's DependencyWarnings should be silenced.150from urllib3.exceptions import DependencyWarning151 152warnings.simplefilter("ignore", DependencyWarning)153 154# Set default logging handler to avoid "No handler found" warnings.155import logging156from logging import NullHandler157 158from . import packages, utils159from .__version__ import (160    __author__,161    __author_email__,162    __build__,163    __cake__,164    __copyright__,165    __description__,166    __license__,167    __title__,168    __url__,169    __version__,170)171from .api import delete, get, head, options, patch, post, put, request172from .exceptions import (173    ConnectionError,174    ConnectTimeout,175    FileModeWarning,176    HTTPError,177    JSONDecodeError,178    ReadTimeout,179    RequestException,180    Timeout,181    TooManyRedirects,182    URLRequired,183)184from .models import PreparedRequest, Request, Response185from .sessions import Session, session186from .status_codes import codes187 188__all__ = (189    "ConnectionError",190    "ConnectTimeout",191    "HTTPError",192    "JSONDecodeError",193    "PreparedRequest",194    "ReadTimeout",195    "Request",196    "RequestException",197    "Response",198    "Session",199    "Timeout",200    "TooManyRedirects",201    "URLRequired",202    "codes",203    "delete",204    "get",205    "head",206    "options",207    "packages",208    "patch",209    "post",210    "put",211    "request",212    "session",213    "utils",214)215 216logging.getLogger(__name__).addHandler(NullHandler())217 218# FileModeWarnings go off per the default.219warnings.simplefilter("default", FileModeWarning, append=True)220 
codekingpro/portable-devtools · Team Ai