Path: blob/master/venv/Lib/site-packages/urllib3/response.py
811 views
from __future__ import absolute_import1from contextlib import contextmanager2import zlib3import io4import logging5from socket import timeout as SocketTimeout6from socket import error as SocketError78try:9import brotli10except ImportError:11brotli = None1213from ._collections import HTTPHeaderDict14from .exceptions import (15BodyNotHttplibCompatible,16ProtocolError,17DecodeError,18ReadTimeoutError,19ResponseNotChunked,20IncompleteRead,21InvalidHeader,22HTTPError,23)24from .packages.six import string_types as basestring, PY325from .packages.six.moves import http_client as httplib26from .connection import HTTPException, BaseSSLError27from .util.response import is_fp_closed, is_response_to_head2829log = logging.getLogger(__name__)303132class DeflateDecoder(object):33def __init__(self):34self._first_try = True35self._data = b""36self._obj = zlib.decompressobj()3738def __getattr__(self, name):39return getattr(self._obj, name)4041def decompress(self, data):42if not data:43return data4445if not self._first_try:46return self._obj.decompress(data)4748self._data += data49try:50decompressed = self._obj.decompress(data)51if decompressed:52self._first_try = False53self._data = None54return decompressed55except zlib.error:56self._first_try = False57self._obj = zlib.decompressobj(-zlib.MAX_WBITS)58try:59return self.decompress(self._data)60finally:61self._data = None626364class GzipDecoderState(object):6566FIRST_MEMBER = 067OTHER_MEMBERS = 168SWALLOW_DATA = 2697071class GzipDecoder(object):72def __init__(self):73self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)74self._state = GzipDecoderState.FIRST_MEMBER7576def __getattr__(self, name):77return getattr(self._obj, name)7879def decompress(self, data):80ret = bytearray()81if self._state == GzipDecoderState.SWALLOW_DATA or not data:82return bytes(ret)83while True:84try:85ret += self._obj.decompress(data)86except zlib.error:87previous_state = self._state88# Ignore data after the first error89self._state = GzipDecoderState.SWALLOW_DATA90if previous_state == GzipDecoderState.OTHER_MEMBERS:91# Allow trailing garbage acceptable in other gzip clients92return bytes(ret)93raise94data = self._obj.unused_data95if not data:96return bytes(ret)97self._state = GzipDecoderState.OTHER_MEMBERS98self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)99100101if brotli is not None:102103class BrotliDecoder(object):104# Supports both 'brotlipy' and 'Brotli' packages105# since they share an import name. The top branches106# are for 'brotlipy' and bottom branches for 'Brotli'107def __init__(self):108self._obj = brotli.Decompressor()109110def decompress(self, data):111if hasattr(self._obj, "decompress"):112return self._obj.decompress(data)113return self._obj.process(data)114115def flush(self):116if hasattr(self._obj, "flush"):117return self._obj.flush()118return b""119120121class MultiDecoder(object):122"""123From RFC7231:124If one or more encodings have been applied to a representation, the125sender that applied the encodings MUST generate a Content-Encoding126header field that lists the content codings in the order in which127they were applied.128"""129130def __init__(self, modes):131self._decoders = [_get_decoder(m.strip()) for m in modes.split(",")]132133def flush(self):134return self._decoders[0].flush()135136def decompress(self, data):137for d in reversed(self._decoders):138data = d.decompress(data)139return data140141142def _get_decoder(mode):143if "," in mode:144return MultiDecoder(mode)145146if mode == "gzip":147return GzipDecoder()148149if brotli is not None and mode == "br":150return BrotliDecoder()151152return DeflateDecoder()153154155class HTTPResponse(io.IOBase):156"""157HTTP Response container.158159Backwards-compatible to httplib's HTTPResponse but the response ``body`` is160loaded and decoded on-demand when the ``data`` property is accessed. This161class is also compatible with the Python standard library's :mod:`io`162module, and can hence be treated as a readable object in the context of that163framework.164165Extra parameters for behaviour not present in httplib.HTTPResponse:166167:param preload_content:168If True, the response's body will be preloaded during construction.169170:param decode_content:171If True, will attempt to decode the body based on the172'content-encoding' header.173174:param original_response:175When this HTTPResponse wrapper is generated from an httplib.HTTPResponse176object, it's convenient to include the original for debug purposes. It's177otherwise unused.178179:param retries:180The retries contains the last :class:`~urllib3.util.retry.Retry` that181was used during the request.182183:param enforce_content_length:184Enforce content length checking. Body returned by server must match185value of Content-Length header, if present. Otherwise, raise error.186"""187188CONTENT_DECODERS = ["gzip", "deflate"]189if brotli is not None:190CONTENT_DECODERS += ["br"]191REDIRECT_STATUSES = [301, 302, 303, 307, 308]192193def __init__(194self,195body="",196headers=None,197status=0,198version=0,199reason=None,200strict=0,201preload_content=True,202decode_content=True,203original_response=None,204pool=None,205connection=None,206msg=None,207retries=None,208enforce_content_length=False,209request_method=None,210request_url=None,211auto_close=True,212):213214if isinstance(headers, HTTPHeaderDict):215self.headers = headers216else:217self.headers = HTTPHeaderDict(headers)218self.status = status219self.version = version220self.reason = reason221self.strict = strict222self.decode_content = decode_content223self.retries = retries224self.enforce_content_length = enforce_content_length225self.auto_close = auto_close226227self._decoder = None228self._body = None229self._fp = None230self._original_response = original_response231self._fp_bytes_read = 0232self.msg = msg233self._request_url = request_url234235if body and isinstance(body, (basestring, bytes)):236self._body = body237238self._pool = pool239self._connection = connection240241if hasattr(body, "read"):242self._fp = body243244# Are we using the chunked-style of transfer encoding?245self.chunked = False246self.chunk_left = None247tr_enc = self.headers.get("transfer-encoding", "").lower()248# Don't incur the penalty of creating a list and then discarding it249encodings = (enc.strip() for enc in tr_enc.split(","))250if "chunked" in encodings:251self.chunked = True252253# Determine length of response254self.length_remaining = self._init_length(request_method)255256# If requested, preload the body.257if preload_content and not self._body:258self._body = self.read(decode_content=decode_content)259260def get_redirect_location(self):261"""262Should we redirect and where to?263264:returns: Truthy redirect location string if we got a redirect status265code and valid location. ``None`` if redirect status and no266location. ``False`` if not a redirect status code.267"""268if self.status in self.REDIRECT_STATUSES:269return self.headers.get("location")270271return False272273def release_conn(self):274if not self._pool or not self._connection:275return276277self._pool._put_conn(self._connection)278self._connection = None279280def drain_conn(self):281"""282Read and discard any remaining HTTP response data in the response connection.283284Unread data in the HTTPResponse connection blocks the connection from being released back to the pool.285"""286try:287self.read()288except (HTTPError, SocketError, BaseSSLError, HTTPException):289pass290291@property292def data(self):293# For backwords-compat with earlier urllib3 0.4 and earlier.294if self._body:295return self._body296297if self._fp:298return self.read(cache_content=True)299300@property301def connection(self):302return self._connection303304def isclosed(self):305return is_fp_closed(self._fp)306307def tell(self):308"""309Obtain the number of bytes pulled over the wire so far. May differ from310the amount of content returned by :meth:``HTTPResponse.read`` if bytes311are encoded on the wire (e.g, compressed).312"""313return self._fp_bytes_read314315def _init_length(self, request_method):316"""317Set initial length value for Response content if available.318"""319length = self.headers.get("content-length")320321if length is not None:322if self.chunked:323# This Response will fail with an IncompleteRead if it can't be324# received as chunked. This method falls back to attempt reading325# the response before raising an exception.326log.warning(327"Received response with both Content-Length and "328"Transfer-Encoding set. This is expressly forbidden "329"by RFC 7230 sec 3.3.2. Ignoring Content-Length and "330"attempting to process response as Transfer-Encoding: "331"chunked."332)333return None334335try:336# RFC 7230 section 3.3.2 specifies multiple content lengths can337# be sent in a single Content-Length header338# (e.g. Content-Length: 42, 42). This line ensures the values339# are all valid ints and that as long as the `set` length is 1,340# all values are the same. Otherwise, the header is invalid.341lengths = set([int(val) for val in length.split(",")])342if len(lengths) > 1:343raise InvalidHeader(344"Content-Length contained multiple "345"unmatching values (%s)" % length346)347length = lengths.pop()348except ValueError:349length = None350else:351if length < 0:352length = None353354# Convert status to int for comparison355# In some cases, httplib returns a status of "_UNKNOWN"356try:357status = int(self.status)358except ValueError:359status = 0360361# Check for responses that shouldn't include a body362if status in (204, 304) or 100 <= status < 200 or request_method == "HEAD":363length = 0364365return length366367def _init_decoder(self):368"""369Set-up the _decoder attribute if necessary.370"""371# Note: content-encoding value should be case-insensitive, per RFC 7230372# Section 3.2373content_encoding = self.headers.get("content-encoding", "").lower()374if self._decoder is None:375if content_encoding in self.CONTENT_DECODERS:376self._decoder = _get_decoder(content_encoding)377elif "," in content_encoding:378encodings = [379e.strip()380for e in content_encoding.split(",")381if e.strip() in self.CONTENT_DECODERS382]383if len(encodings):384self._decoder = _get_decoder(content_encoding)385386DECODER_ERROR_CLASSES = (IOError, zlib.error)387if brotli is not None:388DECODER_ERROR_CLASSES += (brotli.error,)389390def _decode(self, data, decode_content, flush_decoder):391"""392Decode the data passed in and potentially flush the decoder.393"""394if not decode_content:395return data396397try:398if self._decoder:399data = self._decoder.decompress(data)400except self.DECODER_ERROR_CLASSES as e:401content_encoding = self.headers.get("content-encoding", "").lower()402raise DecodeError(403"Received response with content-encoding: %s, but "404"failed to decode it." % content_encoding,405e,406)407if flush_decoder:408data += self._flush_decoder()409410return data411412def _flush_decoder(self):413"""414Flushes the decoder. Should only be called if the decoder is actually415being used.416"""417if self._decoder:418buf = self._decoder.decompress(b"")419return buf + self._decoder.flush()420421return b""422423@contextmanager424def _error_catcher(self):425"""426Catch low-level python exceptions, instead re-raising urllib3427variants, so that low-level exceptions are not leaked in the428high-level api.429430On exit, release the connection back to the pool.431"""432clean_exit = False433434try:435try:436yield437438except SocketTimeout:439# FIXME: Ideally we'd like to include the url in the ReadTimeoutError but440# there is yet no clean way to get at it from this context.441raise ReadTimeoutError(self._pool, None, "Read timed out.")442443except BaseSSLError as e:444# FIXME: Is there a better way to differentiate between SSLErrors?445if "read operation timed out" not in str(e): # Defensive:446# This shouldn't happen but just in case we're missing an edge447# case, let's avoid swallowing SSL errors.448raise449450raise ReadTimeoutError(self._pool, None, "Read timed out.")451452except (HTTPException, SocketError) as e:453# This includes IncompleteRead.454raise ProtocolError("Connection broken: %r" % e, e)455456# If no exception is thrown, we should avoid cleaning up457# unnecessarily.458clean_exit = True459finally:460# If we didn't terminate cleanly, we need to throw away our461# connection.462if not clean_exit:463# The response may not be closed but we're not going to use it464# anymore so close it now to ensure that the connection is465# released back to the pool.466if self._original_response:467self._original_response.close()468469# Closing the response may not actually be sufficient to close470# everything, so if we have a hold of the connection close that471# too.472if self._connection:473self._connection.close()474475# If we hold the original response but it's closed now, we should476# return the connection back to the pool.477if self._original_response and self._original_response.isclosed():478self.release_conn()479480def read(self, amt=None, decode_content=None, cache_content=False):481"""482Similar to :meth:`httplib.HTTPResponse.read`, but with two additional483parameters: ``decode_content`` and ``cache_content``.484485:param amt:486How much of the content to read. If specified, caching is skipped487because it doesn't make sense to cache partial content as the full488response.489490:param decode_content:491If True, will attempt to decode the body based on the492'content-encoding' header.493494:param cache_content:495If True, will save the returned data such that the same result is496returned despite of the state of the underlying file object. This497is useful if you want the ``.data`` property to continue working498after having ``.read()`` the file object. (Overridden if ``amt`` is499set.)500"""501self._init_decoder()502if decode_content is None:503decode_content = self.decode_content504505if self._fp is None:506return507508flush_decoder = False509fp_closed = getattr(self._fp, "closed", False)510511with self._error_catcher():512if amt is None:513# cStringIO doesn't like amt=None514data = self._fp.read() if not fp_closed else b""515flush_decoder = True516else:517cache_content = False518data = self._fp.read(amt) if not fp_closed else b""519if (520amt != 0 and not data521): # Platform-specific: Buggy versions of Python.522# Close the connection when no data is returned523#524# This is redundant to what httplib/http.client _should_525# already do. However, versions of python released before526# December 15, 2012 (http://bugs.python.org/issue16298) do527# not properly close the connection in all cases. There is528# no harm in redundantly calling close.529self._fp.close()530flush_decoder = True531if self.enforce_content_length and self.length_remaining not in (5320,533None,534):535# This is an edge case that httplib failed to cover due536# to concerns of backward compatibility. We're537# addressing it here to make sure IncompleteRead is538# raised during streaming, so all calls with incorrect539# Content-Length are caught.540raise IncompleteRead(self._fp_bytes_read, self.length_remaining)541542if data:543self._fp_bytes_read += len(data)544if self.length_remaining is not None:545self.length_remaining -= len(data)546547data = self._decode(data, decode_content, flush_decoder)548549if cache_content:550self._body = data551552return data553554def stream(self, amt=2 ** 16, decode_content=None):555"""556A generator wrapper for the read() method. A call will block until557``amt`` bytes have been read from the connection or until the558connection is closed.559560:param amt:561How much of the content to read. The generator will return up to562much data per iteration, but may return less. This is particularly563likely when using compressed data. However, the empty string will564never be returned.565566:param decode_content:567If True, will attempt to decode the body based on the568'content-encoding' header.569"""570if self.chunked and self.supports_chunked_reads():571for line in self.read_chunked(amt, decode_content=decode_content):572yield line573else:574while not is_fp_closed(self._fp):575data = self.read(amt=amt, decode_content=decode_content)576577if data:578yield data579580@classmethod581def from_httplib(ResponseCls, r, **response_kw):582"""583Given an :class:`httplib.HTTPResponse` instance ``r``, return a584corresponding :class:`urllib3.response.HTTPResponse` object.585586Remaining parameters are passed to the HTTPResponse constructor, along587with ``original_response=r``.588"""589headers = r.msg590591if not isinstance(headers, HTTPHeaderDict):592if PY3:593headers = HTTPHeaderDict(headers.items())594else:595# Python 2.7596headers = HTTPHeaderDict.from_httplib(headers)597598# HTTPResponse objects in Python 3 don't have a .strict attribute599strict = getattr(r, "strict", 0)600resp = ResponseCls(601body=r,602headers=headers,603status=r.status,604version=r.version,605reason=r.reason,606strict=strict,607original_response=r,608**response_kw609)610return resp611612# Backwards-compatibility methods for httplib.HTTPResponse613def getheaders(self):614return self.headers615616def getheader(self, name, default=None):617return self.headers.get(name, default)618619# Backwards compatibility for http.cookiejar620def info(self):621return self.headers622623# Overrides from io.IOBase624def close(self):625if not self.closed:626self._fp.close()627628if self._connection:629self._connection.close()630631if not self.auto_close:632io.IOBase.close(self)633634@property635def closed(self):636if not self.auto_close:637return io.IOBase.closed.__get__(self)638elif self._fp is None:639return True640elif hasattr(self._fp, "isclosed"):641return self._fp.isclosed()642elif hasattr(self._fp, "closed"):643return self._fp.closed644else:645return True646647def fileno(self):648if self._fp is None:649raise IOError("HTTPResponse has no file to get a fileno from")650elif hasattr(self._fp, "fileno"):651return self._fp.fileno()652else:653raise IOError(654"The file-like object this HTTPResponse is wrapped "655"around has no file descriptor"656)657658def flush(self):659if (660self._fp is not None661and hasattr(self._fp, "flush")662and not getattr(self._fp, "closed", False)663):664return self._fp.flush()665666def readable(self):667# This method is required for `io` module compatibility.668return True669670def readinto(self, b):671# This method is required for `io` module compatibility.672temp = self.read(len(b))673if len(temp) == 0:674return 0675else:676b[: len(temp)] = temp677return len(temp)678679def supports_chunked_reads(self):680"""681Checks if the underlying file-like object looks like a682httplib.HTTPResponse object. We do this by testing for the fp683attribute. If it is present we assume it returns raw chunks as684processed by read_chunked().685"""686return hasattr(self._fp, "fp")687688def _update_chunk_length(self):689# First, we'll figure out length of a chunk and then690# we'll try to read it from socket.691if self.chunk_left is not None:692return693line = self._fp.fp.readline()694line = line.split(b";", 1)[0]695try:696self.chunk_left = int(line, 16)697except ValueError:698# Invalid chunked protocol response, abort.699self.close()700raise httplib.IncompleteRead(line)701702def _handle_chunk(self, amt):703returned_chunk = None704if amt is None:705chunk = self._fp._safe_read(self.chunk_left)706returned_chunk = chunk707self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.708self.chunk_left = None709elif amt < self.chunk_left:710value = self._fp._safe_read(amt)711self.chunk_left = self.chunk_left - amt712returned_chunk = value713elif amt == self.chunk_left:714value = self._fp._safe_read(amt)715self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.716self.chunk_left = None717returned_chunk = value718else: # amt > self.chunk_left719returned_chunk = self._fp._safe_read(self.chunk_left)720self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.721self.chunk_left = None722return returned_chunk723724def read_chunked(self, amt=None, decode_content=None):725"""726Similar to :meth:`HTTPResponse.read`, but with an additional727parameter: ``decode_content``.728729:param amt:730How much of the content to read. If specified, caching is skipped731because it doesn't make sense to cache partial content as the full732response.733734:param decode_content:735If True, will attempt to decode the body based on the736'content-encoding' header.737"""738self._init_decoder()739# FIXME: Rewrite this method and make it a class with a better structured logic.740if not self.chunked:741raise ResponseNotChunked(742"Response is not chunked. "743"Header 'transfer-encoding: chunked' is missing."744)745if not self.supports_chunked_reads():746raise BodyNotHttplibCompatible(747"Body should be httplib.HTTPResponse like. "748"It should have have an fp attribute which returns raw chunks."749)750751with self._error_catcher():752# Don't bother reading the body of a HEAD request.753if self._original_response and is_response_to_head(self._original_response):754self._original_response.close()755return756757# If a response is already read and closed758# then return immediately.759if self._fp.fp is None:760return761762while True:763self._update_chunk_length()764if self.chunk_left == 0:765break766chunk = self._handle_chunk(amt)767decoded = self._decode(768chunk, decode_content=decode_content, flush_decoder=False769)770if decoded:771yield decoded772773if decode_content:774# On CPython and PyPy, we should never need to flush the775# decoder. However, on Jython we *might* need to, so776# lets defensively do it anyway.777decoded = self._flush_decoder()778if decoded: # Platform-specific: Jython.779yield decoded780781# Chunk content ends with \r\n: discard it.782while True:783line = self._fp.fp.readline()784if not line:785# Some sites may not end with '\r\n'.786break787if line == b"\r\n":788break789790# We read everything; close the "file".791if self._original_response:792self._original_response.close()793794def geturl(self):795"""796Returns the URL that was the source of this response.797If the request that generated this response redirected, this method798will return the final redirect location.799"""800if self.retries is not None and len(self.retries.history):801return self.retries.history[-1].redirect_location802else:803return self._request_url804805def __iter__(self):806buffer = []807for chunk in self.stream(decode_content=True):808if b"\n" in chunk:809chunk = chunk.split(b"\n")810yield b"".join(buffer) + chunk[0] + b"\n"811for x in chunk[1:-1]:812yield x + b"\n"813if chunk[-1]:814buffer = [chunk[-1]]815else:816buffer = []817else:818buffer.append(chunk)819if buffer:820yield b"".join(buffer)821822823