Skip to content
Myr

models.py

This file

Path

requests/models.py

900 lines · 31.4 KiB · Python

Last changed by

Merge pull request #3713 from tiran/strict_http_protocol_checkCory Benfieldbefore adoption22ec73d

History of this file

Take it

1# -*- coding: utf-8 -*-23"""4requests.models5~~~~~~~~~~~~~~~67This module contains the primary objects that power Requests.8"""910import collections11import datetime1213# Import encoding now, to avoid implicit import later.14# Implicit import within threads may cause LookupError when standard library is in a ZIP,15# such as in Embedded Python. See https://github.com/kennethreitz/requests/issues/3578.16import encodings.idna1718from io import BytesIO, UnsupportedOperation19from .hooks import default_hooks20from .structures import CaseInsensitiveDict2122from .auth import HTTPBasicAuth23from .cookies import cookiejar_from_dict, get_cookie_header, _copy_cookie_jar24from .packages import idna25from .packages.urllib3.fields import RequestField26from .packages.urllib3.filepost import encode_multipart_formdata27from .packages.urllib3.util import parse_url28from .packages.urllib3.exceptions import (29    DecodeError, ReadTimeoutError, ProtocolError, LocationParseError)30from .exceptions import (31    HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError,32    ContentDecodingError, ConnectionError, StreamConsumedError)33from ._internal_utils import to_native_string34from .utils import (35    guess_filename, get_auth_from_url, requote_uri,36    stream_decode_response_unicode, to_key_val_list, parse_header_links,37    iter_slices, guess_json_utf, super_len, check_header_validity)38from .compat import (39    cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO,40    is_py2, chardet, builtin_str, basestring)41from .compat import json as complexjson42from .status_codes import codes4344#: The set of HTTP status codes that indicate an automatically45#: processable redirect.46REDIRECT_STATI = (47    codes.moved,               # 30148    codes.found,               # 30249    codes.other,               # 30350    codes.temporary_redirect,  # 30751    codes.permanent_redirect,  # 30852)5354DEFAULT_REDIRECT_LIMIT = 3055CONTENT_CHUNK_SIZE = 10 * 102456ITER_CHUNK_SIZE = 512575859class RequestEncodingMixin(object):60    @property61    def path_url(self):62        """Build the path URL to use."""6364        url = []6566        p = urlsplit(self.url)6768        path = p.path69        if not path:70            path = '/'7172        url.append(path)7374        query = p.query75        if query:76            url.append('?')77            url.append(query)7879        return ''.join(url)8081    @staticmethod82    def _encode_params(data):83        """Encode parameters in a piece of data.8485        Will successfully encode parameters when passed as a dict or a list of86        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary87        if parameters are supplied as a dict.88        """8990        if isinstance(data, (str, bytes)):91            return data92        elif hasattr(data, 'read'):93            return data94        elif hasattr(data, '__iter__'):95            result = []96            for k, vs in to_key_val_list(data):97                if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):98                    vs = [vs]99                for v in vs:100                    if v is not None:101                        result.append(102                            (k.encode('utf-8') if isinstance(k, str) else k,103                             v.encode('utf-8') if isinstance(v, str) else v))104            return urlencode(result, doseq=True)105        else:106            return data107108    @staticmethod109    def _encode_files(files, data):110        """Build the body for a multipart/form-data request.111112        Will successfully encode files when passed as a dict or a list of113        tuples. Order is retained if data is a list of tuples but arbitrary114        if parameters are supplied as a dict.115        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)116        or 4-tuples (filename, fileobj, contentype, custom_headers).117        """118        if (not files):119            raise ValueError("Files must be provided.")120        elif isinstance(data, basestring):121            raise ValueError("Data must not be a string.")122123        new_fields = []124        fields = to_key_val_list(data or {})125        files = to_key_val_list(files or {})126127        for field, val in fields:128            if isinstance(val, basestring) or not hasattr(val, '__iter__'):129                val = [val]130            for v in val:131                if v is not None:132                    # Don't call str() on bytestrings: in Py3 it all goes wrong.133                    if not isinstance(v, bytes):134                        v = str(v)135136                    new_fields.append(137                        (field.decode('utf-8') if isinstance(field, bytes) else field,138                         v.encode('utf-8') if isinstance(v, str) else v))139140        for (k, v) in files:141            # support for explicit filename142            ft = None143            fh = None144            if isinstance(v, (tuple, list)):145                if len(v) == 2:146                    fn, fp = v147                elif len(v) == 3:148                    fn, fp, ft = v149                else:150                    fn, fp, ft, fh = v151            else:152                fn = guess_filename(v) or k153                fp = v154155            if isinstance(fp, (str, bytes, bytearray)):156                fdata = fp157            else:158                fdata = fp.read()159160            rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)161            rf.make_multipart(content_type=ft)162            new_fields.append(rf)163164        body, content_type = encode_multipart_formdata(new_fields)165166        return body, content_type167168169class RequestHooksMixin(object):170    def register_hook(self, event, hook):171        """Properly register a hook."""172173        if event not in self.hooks:174            raise ValueError('Unsupported event specified, with event name "%s"' % (event))175176        if isinstance(hook, collections.Callable):177            self.hooks[event].append(hook)178        elif hasattr(hook, '__iter__'):179            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable))180181    def deregister_hook(self, event, hook):182        """Deregister a previously registered hook.183        Returns True if the hook existed, False if not.184        """185186        try:187            self.hooks[event].remove(hook)188            return True189        except ValueError:190            return False191192193class Request(RequestHooksMixin):194    """A user-created :class:`Request <Request>` object.195196    Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.197198    :param method: HTTP method to use.199    :param url: URL to send.200    :param headers: dictionary of headers to send.201    :param files: dictionary of {filename: fileobject} files to multipart upload.202    :param data: the body to attach to the request. If a dictionary is provided, form-encoding will take place.203    :param json: json for the body to attach to the request (if files or data is not specified).204    :param params: dictionary of URL parameters to append to the URL.205    :param auth: Auth handler or (user, pass) tuple.206    :param cookies: dictionary or CookieJar of cookies to attach to this request.207    :param hooks: dictionary of callback hooks, for internal usage.208209    Usage::210211      >>> import requests212      >>> req = requests.Request('GET', 'http://httpbin.org/get')213      >>> req.prepare()214      <PreparedRequest [GET]>215    """216217    def __init__(self, method=None, url=None, headers=None, files=None,218        data=None, params=None, auth=None, cookies=None, hooks=None, json=None):219220        # Default empty dicts for dict params.221        data = [] if data is None else data222        files = [] if files is None else files223        headers = {} if headers is None else headers224        params = {} if params is None else params225        hooks = {} if hooks is None else hooks226227        self.hooks = default_hooks()228        for (k, v) in list(hooks.items()):229            self.register_hook(event=k, hook=v)230231        self.method = method232        self.url = url233        self.headers = headers234        self.files = files235        self.data = data236        self.json = json237        self.params = params238        self.auth = auth239        self.cookies = cookies240241    def __repr__(self):242        return '<Request [%s]>' % (self.method)243244    def prepare(self):245        """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""246        p = PreparedRequest()247        p.prepare(248            method=self.method,249            url=self.url,250            headers=self.headers,251            files=self.files,252            data=self.data,253            json=self.json,254            params=self.params,255            auth=self.auth,256            cookies=self.cookies,257            hooks=self.hooks,258        )259        return p260261262class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):263    """The fully mutable :class:`PreparedRequest <PreparedRequest>` object,264    containing the exact bytes that will be sent to the server.265266    Generated from either a :class:`Request <Request>` object or manually.267268    Usage::269270      >>> import requests271      >>> req = requests.Request('GET', 'http://httpbin.org/get')272      >>> r = req.prepare()273      <PreparedRequest [GET]>274275      >>> s = requests.Session()276      >>> s.send(r)277      <Response [200]>278    """279280    def __init__(self):281        #: HTTP verb to send to the server.282        self.method = None283        #: HTTP URL to send the request to.284        self.url = None285        #: dictionary of HTTP headers.286        self.headers = None287        # The `CookieJar` used to create the Cookie header will be stored here288        # after prepare_cookies is called289        self._cookies = None290        #: request body to send to the server.291        self.body = None292        #: dictionary of callback hooks, for internal usage.293        self.hooks = default_hooks()294        #: integer denoting starting position of a readable file-like body.295        self._body_position = None296297    def prepare(self, method=None, url=None, headers=None, files=None,298        data=None, params=None, auth=None, cookies=None, hooks=None, json=None):299        """Prepares the entire request with the given parameters."""300301        self.prepare_method(method)302        self.prepare_url(url, params)303        self.prepare_headers(headers)304        self.prepare_cookies(cookies)305        self.prepare_body(data, files, json)306        self.prepare_auth(auth, url)307308        # Note that prepare_auth must be last to enable authentication schemes309        # such as OAuth to work on a fully prepared request.310311        # This MUST go after prepare_auth. Authenticators could add a hook312        self.prepare_hooks(hooks)313314    def __repr__(self):315        return '<PreparedRequest [%s]>' % (self.method)316317    def copy(self):318        p = PreparedRequest()319        p.method = self.method320        p.url = self.url321        p.headers = self.headers.copy() if self.headers is not None else None322        p._cookies = _copy_cookie_jar(self._cookies)323        p.body = self.body324        p.hooks = self.hooks325        p._body_position = self._body_position326        return p327328    def prepare_method(self, method):329        """Prepares the given HTTP method."""330        self.method = method331        if self.method is not None:332            self.method = to_native_string(self.method.upper())333334    def prepare_url(self, url, params):335        """Prepares the given HTTP URL."""336        #: Accept objects that have string representations.337        #: We're unable to blindly call unicode/str functions338        #: as this will include the bytestring indicator (b'')339        #: on python 3.x.340        #: https://github.com/kennethreitz/requests/pull/2238341        if isinstance(url, bytes):342            url = url.decode('utf8')343        else:344            url = unicode(url) if is_py2 else str(url)345346        # Remove leading whitespaces from url347        url = url.lstrip()348349        # Don't do any URL preparation for non-HTTP schemes like `mailto`,350        # `data`, `http+unix` etc to work around exceptions from `url_parse`,351        # which handles RFC 3986 only.352        if ':' in url and not url.lower().startswith(('http://', 'https://')):353            self.url = url354            return355356        # Support for unicode domain names and paths.357        try:358            scheme, auth, host, port, path, query, fragment = parse_url(url)359        except LocationParseError as e:360            raise InvalidURL(*e.args)361362        if not scheme:363            error = ("Invalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?")364            error = error.format(to_native_string(url, 'utf8'))365366            raise MissingSchema(error)367368        if not host:369            raise InvalidURL("Invalid URL %r: No host supplied" % url)370371        # Only want to apply IDNA to the hostname372        try:373            host = idna.encode(host, uts46=True).decode('utf-8')374        except (UnicodeError, idna.IDNAError):375            raise InvalidURL('URL has an invalid label.')376377        # Carefully reconstruct the network location378        netloc = auth or ''379        if netloc:380            netloc += '@'381        netloc += host382        if port:383            netloc += ':' + str(port)384385        # Bare domains aren't valid URLs.386        if not path:387            path = '/'388389        if is_py2:390            if isinstance(scheme, str):391                scheme = scheme.encode('utf-8')392            if isinstance(netloc, str):393                netloc = netloc.encode('utf-8')394            if isinstance(path, str):395                path = path.encode('utf-8')396            if isinstance(query, str):397                query = query.encode('utf-8')398            if isinstance(fragment, str):399                fragment = fragment.encode('utf-8')400401        if isinstance(params, (str, bytes)):402            params = to_native_string(params)403404        enc_params = self._encode_params(params)405        if enc_params:406            if query:407                query = '%s&%s' % (query, enc_params)408            else:409                query = enc_params410411        url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))412        self.url = url413414    def prepare_headers(self, headers):415        """Prepares the given HTTP headers."""416417        self.headers = CaseInsensitiveDict()418        if headers:419            for header in headers.items():420                # Raise exception on invalid header value.421                check_header_validity(header)422                name, value = header423                self.headers[to_native_string(name)] = value424425    def prepare_body(self, data, files, json=None):426        """Prepares the given HTTP body data."""427428        # Check if file, fo, generator, iterator.429        # If not, run through normal process.430431        # Nottin' on you.432        body = None433        content_type = None434435        if not data and json is not None:436            # urllib3 requires a bytes-like body. Python 2's json.dumps437            # provides this natively, but Python 3 gives a Unicode string.438            content_type = 'application/json'439            body = complexjson.dumps(json)440            if not isinstance(body, bytes):441                body = body.encode('utf-8')442443        is_stream = all([444            hasattr(data, '__iter__'),445            not isinstance(data, (basestring, list, tuple, collections.Mapping))446        ])447448        try:449            length = super_len(data)450        except (TypeError, AttributeError, UnsupportedOperation):451            length = None452453        if is_stream:454            body = data455456            if getattr(body, 'tell', None) is not None:457                # Record the current file position before reading.458                # This will allow us to rewind a file in the event459                # of a redirect.460                try:461                    self._body_position = body.tell()462                except (IOError, OSError):463                    # This differentiates from None, allowing us to catch464                    # a failed `tell()` later when trying to rewind the body465                    self._body_position = object()466467            if files:468                raise NotImplementedError('Streamed bodies and files are mutually exclusive.')469470            if length:471                self.headers['Content-Length'] = builtin_str(length)472            else:473                self.headers['Transfer-Encoding'] = 'chunked'474        else:475            # Multi-part file uploads.476            if files:477                (body, content_type) = self._encode_files(files, data)478            else:479                if data:480                    body = self._encode_params(data)481                    if isinstance(data, basestring) or hasattr(data, 'read'):482                        content_type = None483                    else:484                        content_type = 'application/x-www-form-urlencoded'485486            self.prepare_content_length(body)487488            # Add content-type if it wasn't explicitly provided.489            if content_type and ('content-type' not in self.headers):490                self.headers['Content-Type'] = content_type491492        self.body = body493494    def prepare_content_length(self, body):495        """Prepare Content-Length header based on request method and body"""496        if body is not None:497            length = super_len(body)498            if length:499                # If length exists, set it. Otherwise, we fallback500                # to Transfer-Encoding: chunked.501                self.headers['Content-Length'] = builtin_str(length)502        elif self.method not in ('GET', 'HEAD') and self.headers.get('Content-Length') is None:503            # Set Content-Length to 0 for methods that can have a body504            # but don't provide one. (i.e. not GET or HEAD)505            self.headers['Content-Length'] = '0'506507    def prepare_auth(self, auth, url=''):508        """Prepares the given HTTP auth data."""509510        # If no Auth is explicitly provided, extract it from the URL first.511        if auth is None:512            url_auth = get_auth_from_url(self.url)513            auth = url_auth if any(url_auth) else None514515        if auth:516            if isinstance(auth, tuple) and len(auth) == 2:517                # special-case basic HTTP auth518                auth = HTTPBasicAuth(*auth)519520            # Allow auth to make its changes.521            r = auth(self)522523            # Update self to reflect the auth changes.524            self.__dict__.update(r.__dict__)525526            # Recompute Content-Length527            self.prepare_content_length(self.body)528529    def prepare_cookies(self, cookies):530        """Prepares the given HTTP cookie data.531532        This function eventually generates a ``Cookie`` header from the533        given cookies using cookielib. Due to cookielib's design, the header534        will not be regenerated if it already exists, meaning this function535        can only be called once for the life of the536        :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls537        to ``prepare_cookies`` will have no actual effect, unless the "Cookie"538        header is removed beforehand.539        """540        if isinstance(cookies, cookielib.CookieJar):541            self._cookies = cookies542        else:543            self._cookies = cookiejar_from_dict(cookies)544545        cookie_header = get_cookie_header(self._cookies, self)546        if cookie_header is not None:547            self.headers['Cookie'] = cookie_header548549    def prepare_hooks(self, hooks):550        """Prepares the given hooks."""551        # hooks can be passed as None to the prepare method and to this552        # method. To prevent iterating over None, simply use an empty list553        # if hooks is False-y554        hooks = hooks or []555        for event in hooks:556            self.register_hook(event, hooks[event])557558559class Response(object):560    """The :class:`Response <Response>` object, which contains a561    server's response to an HTTP request.562    """563564    __attrs__ = [565        '_content', 'status_code', 'headers', 'url', 'history',566        'encoding', 'reason', 'cookies', 'elapsed', 'request'567    ]568569    def __init__(self):570        super(Response, self).__init__()571572        self._content = False573        self._content_consumed = False574575        #: Integer Code of responded HTTP Status, e.g. 404 or 200.576        self.status_code = None577578        #: Case-insensitive Dictionary of Response Headers.579        #: For example, ``headers['content-encoding']`` will return the580        #: value of a ``'Content-Encoding'`` response header.581        self.headers = CaseInsensitiveDict()582583        #: File-like object representation of response (for advanced usage).584        #: Use of ``raw`` requires that ``stream=True`` be set on the request.585        # This requirement does not apply for use internally to Requests.586        self.raw = None587588        #: Final URL location of Response.589        self.url = None590591        #: Encoding to decode with when accessing r.text.592        self.encoding = None593594        #: A list of :class:`Response <Response>` objects from595        #: the history of the Request. Any redirect responses will end596        #: up here. The list is sorted from the oldest to the most recent request.597        self.history = []598599        #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".600        self.reason = None601602        #: A CookieJar of Cookies the server sent back.603        self.cookies = cookiejar_from_dict({})604605        #: The amount of time elapsed between sending the request606        #: and the arrival of the response (as a timedelta).607        #: This property specifically measures the time taken between sending608        #: the first byte of the request and finishing parsing the headers. It609        #: is therefore unaffected by consuming the response content or the610        #: value of the ``stream`` keyword argument.611        self.elapsed = datetime.timedelta(0)612613        #: The :class:`PreparedRequest <PreparedRequest>` object to which this614        #: is a response.615        self.request = None616617    def __getstate__(self):618        # Consume everything; accessing the content attribute makes619        # sure the content has been fully read.620        if not self._content_consumed:621            self.content622623        return dict(624            (attr, getattr(self, attr, None))625            for attr in self.__attrs__626        )627628    def __setstate__(self, state):629        for name, value in state.items():630            setattr(self, name, value)631632        # pickled objects do not have .raw633        setattr(self, '_content_consumed', True)634        setattr(self, 'raw', None)635636    def __repr__(self):637        return '<Response [%s]>' % (self.status_code)638639    def __bool__(self):640        """Returns true if :attr:`status_code` is 'OK'."""641        return self.ok642643    def __nonzero__(self):644        """Returns true if :attr:`status_code` is 'OK'."""645        return self.ok646647    def __iter__(self):648        """Allows you to use a response as an iterator."""649        return self.iter_content(128)650651    @property652    def ok(self):653        try:654            self.raise_for_status()655        except HTTPError:656            return False657        return True658659    @property660    def is_redirect(self):661        """True if this Response is a well-formed HTTP redirect that could have662        been processed automatically (by :meth:`Session.resolve_redirects`).663        """664        return ('location' in self.headers and self.status_code in REDIRECT_STATI)665666    @property667    def is_permanent_redirect(self):668        """True if this Response one of the permanent versions of redirect"""669        return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))670671    @property672    def apparent_encoding(self):673        """The apparent encoding, provided by the chardet library"""674        return chardet.detect(self.content)['encoding']675676    def iter_content(self, chunk_size=1, decode_unicode=False):677        """Iterates over the response data.  When stream=True is set on the678        request, this avoids reading the content at once into memory for679        large responses.  The chunk size is the number of bytes it should680        read into memory.  This is not necessarily the length of each item681        returned as decoding can take place.682683        chunk_size must be of type int or None. A value of None will684        function differently depending on the value of `stream`.685        stream=True will read data as it arrives in whatever size the686        chunks are received. If stream=False, data is returned as687        a single chunk.688689        If decode_unicode is True, content will be decoded using the best690        available encoding based on the response.691        """692693        def generate():694            # Special case for urllib3.695            if hasattr(self.raw, 'stream'):696                try:697                    for chunk in self.raw.stream(chunk_size, decode_content=True):698                        yield chunk699                except ProtocolError as e:700                    raise ChunkedEncodingError(e)701                except DecodeError as e:702                    raise ContentDecodingError(e)703                except ReadTimeoutError as e:704                    raise ConnectionError(e)705            else:706                # Standard file-like object.707                while True:708                    chunk = self.raw.read(chunk_size)709                    if not chunk:710                        break711                    yield chunk712713            self._content_consumed = True714715        if self._content_consumed and isinstance(self._content, bool):716            raise StreamConsumedError()717        elif chunk_size is not None and not isinstance(chunk_size, int):718            raise TypeError("chunk_size must be an int, it is instead a %s." % type(chunk_size))719        # simulate reading small chunks of the content720        reused_chunks = iter_slices(self._content, chunk_size)721722        stream_chunks = generate()723724        chunks = reused_chunks if self._content_consumed else stream_chunks725726        if decode_unicode:727            chunks = stream_decode_response_unicode(chunks, self)728729        return chunks730731    def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None, delimiter=None):732        """Iterates over the response data, one line at a time.  When733        stream=True is set on the request, this avoids reading the734        content at once into memory for large responses.735736        .. note:: This method is not reentrant safe.737        """738739        pending = None740741        for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode):742743            if pending is not None:744                chunk = pending + chunk745746            if delimiter:747                lines = chunk.split(delimiter)748            else:749                lines = chunk.splitlines()750751            if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:752                pending = lines.pop()753            else:754                pending = None755756            for line in lines:757                yield line758759        if pending is not None:760            yield pending761762    @property763    def content(self):764        """Content of the response, in bytes."""765766        if self._content is False:767            # Read the contents.768            if self._content_consumed:769                raise RuntimeError(770                    'The content for this response was already consumed')771772            if self.status_code == 0:773                self._content = None774            else:775                self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()776777        self._content_consumed = True778        # don't need to release the connection; that's been handled by urllib3779        # since we exhausted the data.780        return self._content781782    @property783    def text(self):784        """Content of the response, in unicode.785786        If Response.encoding is None, encoding will be guessed using787        ``chardet``.788789        The encoding of the response content is determined based solely on HTTP790        headers, following RFC 2616 to the letter. If you can take advantage of791        non-HTTP knowledge to make a better guess at the encoding, you should792        set ``r.encoding`` appropriately before accessing this property.793        """794795        # Try charset from content-type796        content = None797        encoding = self.encoding798799        if not self.content:800            return str('')801802        # Fallback to auto-detected encoding.803        if self.encoding is None:804            encoding = self.apparent_encoding805806        # Decode unicode from given encoding.807        try:808            content = str(self.content, encoding, errors='replace')809        except (LookupError, TypeError):810            # A LookupError is raised if the encoding was not found which could811            # indicate a misspelling or similar mistake.812            #813            # A TypeError can be raised if encoding is None814            #815            # So we try blindly encoding.816            content = str(self.content, errors='replace')817818        return content819820    def json(self, **kwargs):821        """Returns the json-encoded content of a response, if any.822823        :param \*\*kwargs: Optional arguments that ``json.loads`` takes.824        :raises ValueError: If the response body does not contain valid json.825        """826827        if not self.encoding and self.content and len(self.content) > 3:828            # No encoding set. JSON RFC 4627 section 3 states we should expect829            # UTF-8, -16 or -32. Detect which one to use; If the detection or830            # decoding fails, fall back to `self.text` (using chardet to make831            # a best guess).832            encoding = guess_json_utf(self.content)833            if encoding is not None:834                try:835                    return complexjson.loads(836                        self.content.decode(encoding), **kwargs837                    )838                except UnicodeDecodeError:839                    # Wrong UTF codec detected; usually because it's not UTF-8840                    # but some other 8-bit codec.  This is an RFC violation,841                    # and the server didn't bother to tell us what codec *was*842                    # used.843                    pass844        return complexjson.loads(self.text, **kwargs)845846    @property847    def links(self):848        """Returns the parsed header links of the response, if any."""849850        header = self.headers.get('link')851852        # l = MultiDict()853        l = {}854855        if header:856            links = parse_header_links(header)857858            for link in links:859                key = link.get('rel') or link.get('url')860                l[key] = link861862        return l863864    def raise_for_status(self):865        """Raises stored :class:`HTTPError`, if one occurred."""866867        http_error_msg = ''868        if isinstance(self.reason, bytes):869            # We attempt to decode utf-8 first because some servers870            # choose to localize their reason strings. If the string871            # isn't utf-8, we fall back to iso-8859-1 for all other872            # encodings. (See PR #3538)873            try:874                reason = self.reason.decode('utf-8')875            except UnicodeDecodeError:876                reason = self.reason.decode('iso-8859-1')877        else:878            reason = self.reason879880        if 400 <= self.status_code < 500:881            http_error_msg = u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url)882883        elif 500 <= self.status_code < 600:884            http_error_msg = u'%s Server Error: %s for url: %s' % (self.status_code, reason, self.url)885886        if http_error_msg:887            raise HTTPError(http_error_msg, response=self)888889    def close(self):890        """Releases the connection back to the pool. Once this method has been891        called the underlying ``raw`` object must not be accessed again.892893        *Note: Should not normally need to be called explicitly.*894        """895        if not self._content_consumed:896            self.raw.close()897898        release_conn = getattr(self.raw, 'release_conn', None)899        if release_conn is not None:900            release_conn()