Path: blob/master/venv/Lib/site-packages/requests/models.py
811 views
# -*- coding: utf-8 -*-12"""3requests.models4~~~~~~~~~~~~~~~56This module contains the primary objects that power Requests.7"""89import datetime10import sys1112# Import encoding now, to avoid implicit import later.13# Implicit import within threads may cause LookupError when standard library is in a ZIP,14# such as in Embedded Python. See https://github.com/psf/requests/issues/3578.15import encodings.idna1617from urllib3.fields import RequestField18from urllib3.filepost import encode_multipart_formdata19from urllib3.util import parse_url20from urllib3.exceptions import (21DecodeError, ReadTimeoutError, ProtocolError, LocationParseError)2223from io import UnsupportedOperation24from .hooks import default_hooks25from .structures import CaseInsensitiveDict2627from .auth import HTTPBasicAuth28from .cookies import cookiejar_from_dict, get_cookie_header, _copy_cookie_jar29from .exceptions import (30HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError,31ContentDecodingError, ConnectionError, StreamConsumedError)32from ._internal_utils import to_native_string, unicode_is_ascii33from .utils import (34guess_filename, get_auth_from_url, requote_uri,35stream_decode_response_unicode, to_key_val_list, parse_header_links,36iter_slices, guess_json_utf, super_len, check_header_validity)37from .compat import (38Callable, Mapping,39cookielib, urlunparse, urlsplit, urlencode, str, bytes,40is_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 = (47codes.moved, # 30148codes.found, # 30249codes.other, # 30350codes.temporary_redirect, # 30751codes.permanent_redirect, # 30852)5354DEFAULT_REDIRECT_LIMIT = 3055CONTENT_CHUNK_SIZE = 10 * 102456ITER_CHUNK_SIZE = 512575859class RequestEncodingMixin(object):60@property61def path_url(self):62"""Build the path URL to use."""6364url = []6566p = urlsplit(self.url)6768path = p.path69if not path:70path = '/'7172url.append(path)7374query = p.query75if query:76url.append('?')77url.append(query)7879return ''.join(url)8081@staticmethod82def _encode_params(data):83"""Encode parameters in a piece of data.8485Will successfully encode parameters when passed as a dict or a list of862-tuples. Order is retained if data is a list of 2-tuples but arbitrary87if parameters are supplied as a dict.88"""8990if isinstance(data, (str, bytes)):91return data92elif hasattr(data, 'read'):93return data94elif hasattr(data, '__iter__'):95result = []96for k, vs in to_key_val_list(data):97if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):98vs = [vs]99for v in vs:100if v is not None:101result.append(102(k.encode('utf-8') if isinstance(k, str) else k,103v.encode('utf-8') if isinstance(v, str) else v))104return urlencode(result, doseq=True)105else:106return data107108@staticmethod109def _encode_files(files, data):110"""Build the body for a multipart/form-data request.111112Will successfully encode files when passed as a dict or a list of113tuples. Order is retained if data is a list of tuples but arbitrary114if parameters are supplied as a dict.115The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)116or 4-tuples (filename, fileobj, contentype, custom_headers).117"""118if (not files):119raise ValueError("Files must be provided.")120elif isinstance(data, basestring):121raise ValueError("Data must not be a string.")122123new_fields = []124fields = to_key_val_list(data or {})125files = to_key_val_list(files or {})126127for field, val in fields:128if isinstance(val, basestring) or not hasattr(val, '__iter__'):129val = [val]130for v in val:131if v is not None:132# Don't call str() on bytestrings: in Py3 it all goes wrong.133if not isinstance(v, bytes):134v = str(v)135136new_fields.append(137(field.decode('utf-8') if isinstance(field, bytes) else field,138v.encode('utf-8') if isinstance(v, str) else v))139140for (k, v) in files:141# support for explicit filename142ft = None143fh = None144if isinstance(v, (tuple, list)):145if len(v) == 2:146fn, fp = v147elif len(v) == 3:148fn, fp, ft = v149else:150fn, fp, ft, fh = v151else:152fn = guess_filename(v) or k153fp = v154155if isinstance(fp, (str, bytes, bytearray)):156fdata = fp157elif hasattr(fp, 'read'):158fdata = fp.read()159elif fp is None:160continue161else:162fdata = fp163164rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)165rf.make_multipart(content_type=ft)166new_fields.append(rf)167168body, content_type = encode_multipart_formdata(new_fields)169170return body, content_type171172173class RequestHooksMixin(object):174def register_hook(self, event, hook):175"""Properly register a hook."""176177if event not in self.hooks:178raise ValueError('Unsupported event specified, with event name "%s"' % (event))179180if isinstance(hook, Callable):181self.hooks[event].append(hook)182elif hasattr(hook, '__iter__'):183self.hooks[event].extend(h for h in hook if isinstance(h, Callable))184185def deregister_hook(self, event, hook):186"""Deregister a previously registered hook.187Returns True if the hook existed, False if not.188"""189190try:191self.hooks[event].remove(hook)192return True193except ValueError:194return False195196197class Request(RequestHooksMixin):198"""A user-created :class:`Request <Request>` object.199200Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.201202:param method: HTTP method to use.203:param url: URL to send.204:param headers: dictionary of headers to send.205:param files: dictionary of {filename: fileobject} files to multipart upload.206:param data: the body to attach to the request. If a dictionary or207list of tuples ``[(key, value)]`` is provided, form-encoding will208take place.209:param json: json for the body to attach to the request (if files or data is not specified).210:param params: URL parameters to append to the URL. If a dictionary or211list of tuples ``[(key, value)]`` is provided, form-encoding will212take place.213:param auth: Auth handler or (user, pass) tuple.214:param cookies: dictionary or CookieJar of cookies to attach to this request.215:param hooks: dictionary of callback hooks, for internal usage.216217Usage::218219>>> import requests220>>> req = requests.Request('GET', 'https://httpbin.org/get')221>>> req.prepare()222<PreparedRequest [GET]>223"""224225def __init__(self,226method=None, url=None, headers=None, files=None, data=None,227params=None, auth=None, cookies=None, hooks=None, json=None):228229# Default empty dicts for dict params.230data = [] if data is None else data231files = [] if files is None else files232headers = {} if headers is None else headers233params = {} if params is None else params234hooks = {} if hooks is None else hooks235236self.hooks = default_hooks()237for (k, v) in list(hooks.items()):238self.register_hook(event=k, hook=v)239240self.method = method241self.url = url242self.headers = headers243self.files = files244self.data = data245self.json = json246self.params = params247self.auth = auth248self.cookies = cookies249250def __repr__(self):251return '<Request [%s]>' % (self.method)252253def prepare(self):254"""Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""255p = PreparedRequest()256p.prepare(257method=self.method,258url=self.url,259headers=self.headers,260files=self.files,261data=self.data,262json=self.json,263params=self.params,264auth=self.auth,265cookies=self.cookies,266hooks=self.hooks,267)268return p269270271class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):272"""The fully mutable :class:`PreparedRequest <PreparedRequest>` object,273containing the exact bytes that will be sent to the server.274275Generated from either a :class:`Request <Request>` object or manually.276277Usage::278279>>> import requests280>>> req = requests.Request('GET', 'https://httpbin.org/get')281>>> r = req.prepare()282>>> r283<PreparedRequest [GET]>284285>>> s = requests.Session()286>>> s.send(r)287<Response [200]>288"""289290def __init__(self):291#: HTTP verb to send to the server.292self.method = None293#: HTTP URL to send the request to.294self.url = None295#: dictionary of HTTP headers.296self.headers = None297# The `CookieJar` used to create the Cookie header will be stored here298# after prepare_cookies is called299self._cookies = None300#: request body to send to the server.301self.body = None302#: dictionary of callback hooks, for internal usage.303self.hooks = default_hooks()304#: integer denoting starting position of a readable file-like body.305self._body_position = None306307def prepare(self,308method=None, url=None, headers=None, files=None, data=None,309params=None, auth=None, cookies=None, hooks=None, json=None):310"""Prepares the entire request with the given parameters."""311312self.prepare_method(method)313self.prepare_url(url, params)314self.prepare_headers(headers)315self.prepare_cookies(cookies)316self.prepare_body(data, files, json)317self.prepare_auth(auth, url)318319# Note that prepare_auth must be last to enable authentication schemes320# such as OAuth to work on a fully prepared request.321322# This MUST go after prepare_auth. Authenticators could add a hook323self.prepare_hooks(hooks)324325def __repr__(self):326return '<PreparedRequest [%s]>' % (self.method)327328def copy(self):329p = PreparedRequest()330p.method = self.method331p.url = self.url332p.headers = self.headers.copy() if self.headers is not None else None333p._cookies = _copy_cookie_jar(self._cookies)334p.body = self.body335p.hooks = self.hooks336p._body_position = self._body_position337return p338339def prepare_method(self, method):340"""Prepares the given HTTP method."""341self.method = method342if self.method is not None:343self.method = to_native_string(self.method.upper())344345@staticmethod346def _get_idna_encoded_host(host):347import idna348349try:350host = idna.encode(host, uts46=True).decode('utf-8')351except idna.IDNAError:352raise UnicodeError353return host354355def prepare_url(self, url, params):356"""Prepares the given HTTP URL."""357#: Accept objects that have string representations.358#: We're unable to blindly call unicode/str functions359#: as this will include the bytestring indicator (b'')360#: on python 3.x.361#: https://github.com/psf/requests/pull/2238362if isinstance(url, bytes):363url = url.decode('utf8')364else:365url = unicode(url) if is_py2 else str(url)366367# Remove leading whitespaces from url368url = url.lstrip()369370# Don't do any URL preparation for non-HTTP schemes like `mailto`,371# `data` etc to work around exceptions from `url_parse`, which372# handles RFC 3986 only.373if ':' in url and not url.lower().startswith('http'):374self.url = url375return376377# Support for unicode domain names and paths.378try:379scheme, auth, host, port, path, query, fragment = parse_url(url)380except LocationParseError as e:381raise InvalidURL(*e.args)382383if not scheme:384error = ("Invalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?")385error = error.format(to_native_string(url, 'utf8'))386387raise MissingSchema(error)388389if not host:390raise InvalidURL("Invalid URL %r: No host supplied" % url)391392# In general, we want to try IDNA encoding the hostname if the string contains393# non-ASCII characters. This allows users to automatically get the correct IDNA394# behaviour. For strings containing only ASCII characters, we need to also verify395# it doesn't start with a wildcard (*), before allowing the unencoded hostname.396if not unicode_is_ascii(host):397try:398host = self._get_idna_encoded_host(host)399except UnicodeError:400raise InvalidURL('URL has an invalid label.')401elif host.startswith(u'*'):402raise InvalidURL('URL has an invalid label.')403404# Carefully reconstruct the network location405netloc = auth or ''406if netloc:407netloc += '@'408netloc += host409if port:410netloc += ':' + str(port)411412# Bare domains aren't valid URLs.413if not path:414path = '/'415416if is_py2:417if isinstance(scheme, str):418scheme = scheme.encode('utf-8')419if isinstance(netloc, str):420netloc = netloc.encode('utf-8')421if isinstance(path, str):422path = path.encode('utf-8')423if isinstance(query, str):424query = query.encode('utf-8')425if isinstance(fragment, str):426fragment = fragment.encode('utf-8')427428if isinstance(params, (str, bytes)):429params = to_native_string(params)430431enc_params = self._encode_params(params)432if enc_params:433if query:434query = '%s&%s' % (query, enc_params)435else:436query = enc_params437438url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))439self.url = url440441def prepare_headers(self, headers):442"""Prepares the given HTTP headers."""443444self.headers = CaseInsensitiveDict()445if headers:446for header in headers.items():447# Raise exception on invalid header value.448check_header_validity(header)449name, value = header450self.headers[to_native_string(name)] = value451452def prepare_body(self, data, files, json=None):453"""Prepares the given HTTP body data."""454455# Check if file, fo, generator, iterator.456# If not, run through normal process.457458# Nottin' on you.459body = None460content_type = None461462if not data and json is not None:463# urllib3 requires a bytes-like body. Python 2's json.dumps464# provides this natively, but Python 3 gives a Unicode string.465content_type = 'application/json'466body = complexjson.dumps(json)467if not isinstance(body, bytes):468body = body.encode('utf-8')469470is_stream = all([471hasattr(data, '__iter__'),472not isinstance(data, (basestring, list, tuple, Mapping))473])474475if is_stream:476try:477length = super_len(data)478except (TypeError, AttributeError, UnsupportedOperation):479length = None480481body = data482483if getattr(body, 'tell', None) is not None:484# Record the current file position before reading.485# This will allow us to rewind a file in the event486# of a redirect.487try:488self._body_position = body.tell()489except (IOError, OSError):490# This differentiates from None, allowing us to catch491# a failed `tell()` later when trying to rewind the body492self._body_position = object()493494if files:495raise NotImplementedError('Streamed bodies and files are mutually exclusive.')496497if length:498self.headers['Content-Length'] = builtin_str(length)499else:500self.headers['Transfer-Encoding'] = 'chunked'501else:502# Multi-part file uploads.503if files:504(body, content_type) = self._encode_files(files, data)505else:506if data:507body = self._encode_params(data)508if isinstance(data, basestring) or hasattr(data, 'read'):509content_type = None510else:511content_type = 'application/x-www-form-urlencoded'512513self.prepare_content_length(body)514515# Add content-type if it wasn't explicitly provided.516if content_type and ('content-type' not in self.headers):517self.headers['Content-Type'] = content_type518519self.body = body520521def prepare_content_length(self, body):522"""Prepare Content-Length header based on request method and body"""523if body is not None:524length = super_len(body)525if length:526# If length exists, set it. Otherwise, we fallback527# to Transfer-Encoding: chunked.528self.headers['Content-Length'] = builtin_str(length)529elif self.method not in ('GET', 'HEAD') and self.headers.get('Content-Length') is None:530# Set Content-Length to 0 for methods that can have a body531# but don't provide one. (i.e. not GET or HEAD)532self.headers['Content-Length'] = '0'533534def prepare_auth(self, auth, url=''):535"""Prepares the given HTTP auth data."""536537# If no Auth is explicitly provided, extract it from the URL first.538if auth is None:539url_auth = get_auth_from_url(self.url)540auth = url_auth if any(url_auth) else None541542if auth:543if isinstance(auth, tuple) and len(auth) == 2:544# special-case basic HTTP auth545auth = HTTPBasicAuth(*auth)546547# Allow auth to make its changes.548r = auth(self)549550# Update self to reflect the auth changes.551self.__dict__.update(r.__dict__)552553# Recompute Content-Length554self.prepare_content_length(self.body)555556def prepare_cookies(self, cookies):557"""Prepares the given HTTP cookie data.558559This function eventually generates a ``Cookie`` header from the560given cookies using cookielib. Due to cookielib's design, the header561will not be regenerated if it already exists, meaning this function562can only be called once for the life of the563:class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls564to ``prepare_cookies`` will have no actual effect, unless the "Cookie"565header is removed beforehand.566"""567if isinstance(cookies, cookielib.CookieJar):568self._cookies = cookies569else:570self._cookies = cookiejar_from_dict(cookies)571572cookie_header = get_cookie_header(self._cookies, self)573if cookie_header is not None:574self.headers['Cookie'] = cookie_header575576def prepare_hooks(self, hooks):577"""Prepares the given hooks."""578# hooks can be passed as None to the prepare method and to this579# method. To prevent iterating over None, simply use an empty list580# if hooks is False-y581hooks = hooks or []582for event in hooks:583self.register_hook(event, hooks[event])584585586class Response(object):587"""The :class:`Response <Response>` object, which contains a588server's response to an HTTP request.589"""590591__attrs__ = [592'_content', 'status_code', 'headers', 'url', 'history',593'encoding', 'reason', 'cookies', 'elapsed', 'request'594]595596def __init__(self):597self._content = False598self._content_consumed = False599self._next = None600601#: Integer Code of responded HTTP Status, e.g. 404 or 200.602self.status_code = None603604#: Case-insensitive Dictionary of Response Headers.605#: For example, ``headers['content-encoding']`` will return the606#: value of a ``'Content-Encoding'`` response header.607self.headers = CaseInsensitiveDict()608609#: File-like object representation of response (for advanced usage).610#: Use of ``raw`` requires that ``stream=True`` be set on the request.611#: This requirement does not apply for use internally to Requests.612self.raw = None613614#: Final URL location of Response.615self.url = None616617#: Encoding to decode with when accessing r.text.618self.encoding = None619620#: A list of :class:`Response <Response>` objects from621#: the history of the Request. Any redirect responses will end622#: up here. The list is sorted from the oldest to the most recent request.623self.history = []624625#: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".626self.reason = None627628#: A CookieJar of Cookies the server sent back.629self.cookies = cookiejar_from_dict({})630631#: The amount of time elapsed between sending the request632#: and the arrival of the response (as a timedelta).633#: This property specifically measures the time taken between sending634#: the first byte of the request and finishing parsing the headers. It635#: is therefore unaffected by consuming the response content or the636#: value of the ``stream`` keyword argument.637self.elapsed = datetime.timedelta(0)638639#: The :class:`PreparedRequest <PreparedRequest>` object to which this640#: is a response.641self.request = None642643def __enter__(self):644return self645646def __exit__(self, *args):647self.close()648649def __getstate__(self):650# Consume everything; accessing the content attribute makes651# sure the content has been fully read.652if not self._content_consumed:653self.content654655return {attr: getattr(self, attr, None) for attr in self.__attrs__}656657def __setstate__(self, state):658for name, value in state.items():659setattr(self, name, value)660661# pickled objects do not have .raw662setattr(self, '_content_consumed', True)663setattr(self, 'raw', None)664665def __repr__(self):666return '<Response [%s]>' % (self.status_code)667668def __bool__(self):669"""Returns True if :attr:`status_code` is less than 400.670671This attribute checks if the status code of the response is between672400 and 600 to see if there was a client error or a server error. If673the status code, is between 200 and 400, this will return True. This674is **not** a check to see if the response code is ``200 OK``.675"""676return self.ok677678def __nonzero__(self):679"""Returns True if :attr:`status_code` is less than 400.680681This attribute checks if the status code of the response is between682400 and 600 to see if there was a client error or a server error. If683the status code, is between 200 and 400, this will return True. This684is **not** a check to see if the response code is ``200 OK``.685"""686return self.ok687688def __iter__(self):689"""Allows you to use a response as an iterator."""690return self.iter_content(128)691692@property693def ok(self):694"""Returns True if :attr:`status_code` is less than 400, False if not.695696This attribute checks if the status code of the response is between697400 and 600 to see if there was a client error or a server error. If698the status code is between 200 and 400, this will return True. This699is **not** a check to see if the response code is ``200 OK``.700"""701try:702self.raise_for_status()703except HTTPError:704return False705return True706707@property708def is_redirect(self):709"""True if this Response is a well-formed HTTP redirect that could have710been processed automatically (by :meth:`Session.resolve_redirects`).711"""712return ('location' in self.headers and self.status_code in REDIRECT_STATI)713714@property715def is_permanent_redirect(self):716"""True if this Response one of the permanent versions of redirect."""717return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))718719@property720def next(self):721"""Returns a PreparedRequest for the next request in a redirect chain, if there is one."""722return self._next723724@property725def apparent_encoding(self):726"""The apparent encoding, provided by the chardet library."""727return chardet.detect(self.content)['encoding']728729def iter_content(self, chunk_size=1, decode_unicode=False):730"""Iterates over the response data. When stream=True is set on the731request, this avoids reading the content at once into memory for732large responses. The chunk size is the number of bytes it should733read into memory. This is not necessarily the length of each item734returned as decoding can take place.735736chunk_size must be of type int or None. A value of None will737function differently depending on the value of `stream`.738stream=True will read data as it arrives in whatever size the739chunks are received. If stream=False, data is returned as740a single chunk.741742If decode_unicode is True, content will be decoded using the best743available encoding based on the response.744"""745746def generate():747# Special case for urllib3.748if hasattr(self.raw, 'stream'):749try:750for chunk in self.raw.stream(chunk_size, decode_content=True):751yield chunk752except ProtocolError as e:753raise ChunkedEncodingError(e)754except DecodeError as e:755raise ContentDecodingError(e)756except ReadTimeoutError as e:757raise ConnectionError(e)758else:759# Standard file-like object.760while True:761chunk = self.raw.read(chunk_size)762if not chunk:763break764yield chunk765766self._content_consumed = True767768if self._content_consumed and isinstance(self._content, bool):769raise StreamConsumedError()770elif chunk_size is not None and not isinstance(chunk_size, int):771raise TypeError("chunk_size must be an int, it is instead a %s." % type(chunk_size))772# simulate reading small chunks of the content773reused_chunks = iter_slices(self._content, chunk_size)774775stream_chunks = generate()776777chunks = reused_chunks if self._content_consumed else stream_chunks778779if decode_unicode:780chunks = stream_decode_response_unicode(chunks, self)781782return chunks783784def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None):785"""Iterates over the response data, one line at a time. When786stream=True is set on the request, this avoids reading the787content at once into memory for large responses.788789.. note:: This method is not reentrant safe.790"""791792pending = None793794for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode):795796if pending is not None:797chunk = pending + chunk798799if delimiter:800lines = chunk.split(delimiter)801else:802lines = chunk.splitlines()803804if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:805pending = lines.pop()806else:807pending = None808809for line in lines:810yield line811812if pending is not None:813yield pending814815@property816def content(self):817"""Content of the response, in bytes."""818819if self._content is False:820# Read the contents.821if self._content_consumed:822raise RuntimeError(823'The content for this response was already consumed')824825if self.status_code == 0 or self.raw is None:826self._content = None827else:828self._content = b''.join(self.iter_content(CONTENT_CHUNK_SIZE)) or b''829830self._content_consumed = True831# don't need to release the connection; that's been handled by urllib3832# since we exhausted the data.833return self._content834835@property836def text(self):837"""Content of the response, in unicode.838839If Response.encoding is None, encoding will be guessed using840``chardet``.841842The encoding of the response content is determined based solely on HTTP843headers, following RFC 2616 to the letter. If you can take advantage of844non-HTTP knowledge to make a better guess at the encoding, you should845set ``r.encoding`` appropriately before accessing this property.846"""847848# Try charset from content-type849content = None850encoding = self.encoding851852if not self.content:853return str('')854855# Fallback to auto-detected encoding.856if self.encoding is None:857encoding = self.apparent_encoding858859# Decode unicode from given encoding.860try:861content = str(self.content, encoding, errors='replace')862except (LookupError, TypeError):863# A LookupError is raised if the encoding was not found which could864# indicate a misspelling or similar mistake.865#866# A TypeError can be raised if encoding is None867#868# So we try blindly encoding.869content = str(self.content, errors='replace')870871return content872873def json(self, **kwargs):874r"""Returns the json-encoded content of a response, if any.875876:param \*\*kwargs: Optional arguments that ``json.loads`` takes.877:raises ValueError: If the response body does not contain valid json.878"""879880if not self.encoding and self.content and len(self.content) > 3:881# No encoding set. JSON RFC 4627 section 3 states we should expect882# UTF-8, -16 or -32. Detect which one to use; If the detection or883# decoding fails, fall back to `self.text` (using chardet to make884# a best guess).885encoding = guess_json_utf(self.content)886if encoding is not None:887try:888return complexjson.loads(889self.content.decode(encoding), **kwargs890)891except UnicodeDecodeError:892# Wrong UTF codec detected; usually because it's not UTF-8893# but some other 8-bit codec. This is an RFC violation,894# and the server didn't bother to tell us what codec *was*895# used.896pass897return complexjson.loads(self.text, **kwargs)898899@property900def links(self):901"""Returns the parsed header links of the response, if any."""902903header = self.headers.get('link')904905# l = MultiDict()906l = {}907908if header:909links = parse_header_links(header)910911for link in links:912key = link.get('rel') or link.get('url')913l[key] = link914915return l916917def raise_for_status(self):918"""Raises :class:`HTTPError`, if one occurred."""919920http_error_msg = ''921if isinstance(self.reason, bytes):922# We attempt to decode utf-8 first because some servers923# choose to localize their reason strings. If the string924# isn't utf-8, we fall back to iso-8859-1 for all other925# encodings. (See PR #3538)926try:927reason = self.reason.decode('utf-8')928except UnicodeDecodeError:929reason = self.reason.decode('iso-8859-1')930else:931reason = self.reason932933if 400 <= self.status_code < 500:934http_error_msg = u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url)935936elif 500 <= self.status_code < 600:937http_error_msg = u'%s Server Error: %s for url: %s' % (self.status_code, reason, self.url)938939if http_error_msg:940raise HTTPError(http_error_msg, response=self)941942def close(self):943"""Releases the connection back to the pool. Once this method has been944called the underlying ``raw`` object must not be accessed again.945946*Note: Should not normally need to be called explicitly.*947"""948if not self._content_consumed:949self.raw.close()950951release_conn = getattr(self.raw, 'release_conn', None)952if release_conn is not None:953release_conn()954955956