We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
socket.timeout not wrapped properly
As mentioned in a [comment](https://github.com/kennethreitz/requests/issues/1787#issuecomment-30510686) on kennethreitz/requests#1787 urllib3 apparently lets a `socket.timeout` exception propagate outside library code instead of wrapping it e.g. with `urllib3.exceptions.TimeoutError`. See the linked issue for a full backtrace.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `urllib3/response.py`
Content:
```
1 # urllib3/response.py
2 # Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
3 #
4 # This module is part of urllib3 and is released under
5 # the MIT License: http://www.opensource.org/licenses/mit-license.php
6 
7 
8 import logging
9 import zlib
10 import io
11 
12 from ._collections import HTTPHeaderDict
13 from .exceptions import DecodeError
14 from .packages.six import string_types as basestring, binary_type
15 from .util import is_fp_closed
16 
17 
18 log = logging.getLogger(__name__)
19 
20 
21 class DeflateDecoder(object):
22 
23     def __init__(self):
24         self._first_try = True
25         self._data = binary_type()
26         self._obj = zlib.decompressobj()
27 
28     def __getattr__(self, name):
29         return getattr(self._obj, name)
30 
31     def decompress(self, data):
32         if not self._first_try:
33             return self._obj.decompress(data)
34 
35         self._data += data
36         try:
37             return self._obj.decompress(data)
38         except zlib.error:
39             self._first_try = False
40             self._obj = zlib.decompressobj(-zlib.MAX_WBITS)
41             try:
42                 return self.decompress(self._data)
43             finally:
44                 self._data = None
45 
46 
47 def _get_decoder(mode):
48     if mode == 'gzip':
49         return zlib.decompressobj(16 + zlib.MAX_WBITS)
50 
51     return DeflateDecoder()
52 
53 
54 class HTTPResponse(io.IOBase):
55     """
56     HTTP Response container.
57 
58     Backwards-compatible to httplib's HTTPResponse but the response ``body`` is
59     loaded and decoded on-demand when the ``data`` property is accessed.
60 
61     Extra parameters for behaviour not present in httplib.HTTPResponse:
62 
63     :param preload_content:
64         If True, the response's body will be preloaded during construction.
65 
66     :param decode_content:
67         If True, attempts to decode specific content-encoding's based on headers
68         (like 'gzip' and 'deflate') will be skipped and raw data will be used
69         instead.
70 
71     :param original_response:
72         When this HTTPResponse wrapper is generated from an httplib.HTTPResponse
73         object, it's convenient to include the original for debug purposes. It's
74         otherwise unused.
75     """
76 
77     CONTENT_DECODERS = ['gzip', 'deflate']
78     REDIRECT_STATUSES = [301, 302, 303, 307, 308]
79 
80     def __init__(self, body='', headers=None, status=0, version=0, reason=None,
81                  strict=0, preload_content=True, decode_content=True,
82                  original_response=None, pool=None, connection=None):
83 
84         self.headers = HTTPHeaderDict()
85         if headers:
86             self.headers.update(headers)
87         self.status = status
88         self.version = version
89         self.reason = reason
90         self.strict = strict
91         self.decode_content = decode_content
92 
93         self._decoder = None
94         self._body = body if body and isinstance(body, basestring) else None
95         self._fp = None
96         self._original_response = original_response
97         self._fp_bytes_read = 0
98 
99         self._pool = pool
100         self._connection = connection
101 
102         if hasattr(body, 'read'):
103             self._fp = body
104 
105         if preload_content and not self._body:
106             self._body = self.read(decode_content=decode_content)
107 
108     def get_redirect_location(self):
109         """
110         Should we redirect and where to?
111 
112         :returns: Truthy redirect location string if we got a redirect status
113             code and valid location. ``None`` if redirect status and no
114             location. ``False`` if not a redirect status code.
115         """
116         if self.status in self.REDIRECT_STATUSES:
117             return self.headers.get('location')
118 
119         return False
120 
121     def release_conn(self):
122         if not self._pool or not self._connection:
123             return
124 
125         self._pool._put_conn(self._connection)
126         self._connection = None
127 
128     @property
129     def data(self):
130         # For backwords-compat with earlier urllib3 0.4 and earlier.
131         if self._body:
132             return self._body
133 
134         if self._fp:
135             return self.read(cache_content=True)
136 
137     def tell(self):
138         """
139         Obtain the number of bytes pulled over the wire so far. May differ from
140         the amount of content returned by :meth:``HTTPResponse.read`` if bytes
141         are encoded on the wire (e.g, compressed).
142         """
143         return self._fp_bytes_read
144 
145     def read(self, amt=None, decode_content=None, cache_content=False):
146         """
147         Similar to :meth:`httplib.HTTPResponse.read`, but with two additional
148         parameters: ``decode_content`` and ``cache_content``.
149 
150         :param amt:
151             How much of the content to read. If specified, caching is skipped
152             because it doesn't make sense to cache partial content as the full
153             response.
154 
155         :param decode_content:
156             If True, will attempt to decode the body based on the
157             'content-encoding' header.
158 
159         :param cache_content:
160             If True, will save the returned data such that the same result is
161             returned despite of the state of the underlying file object. This
162             is useful if you want the ``.data`` property to continue working
163             after having ``.read()`` the file object. (Overridden if ``amt`` is
164             set.)
165         """
166         # Note: content-encoding value should be case-insensitive, per RFC 2616
167         # Section 3.5
168         content_encoding = self.headers.get('content-encoding', '').lower()
169         if self._decoder is None:
170             if content_encoding in self.CONTENT_DECODERS:
171                 self._decoder = _get_decoder(content_encoding)
172         if decode_content is None:
173             decode_content = self.decode_content
174 
175         if self._fp is None:
176             return
177 
178         flush_decoder = False
179 
180         try:
181             if amt is None:
182                 # cStringIO doesn't like amt=None
183                 data = self._fp.read()
184                 flush_decoder = True
185             else:
186                 cache_content = False
187                 data = self._fp.read(amt)
188                 if amt != 0 and not data:  # Platform-specific: Buggy versions of Python.
189                     # Close the connection when no data is returned
190                     #
191                     # This is redundant to what httplib/http.client _should_
192                     # already do.  However, versions of python released before
193                     # December 15, 2012 (http://bugs.python.org/issue16298) do
194                     # not properly close the connection in all cases. There is
195                     # no harm in redundantly calling close.
196                     self._fp.close()
197                     flush_decoder = True
198 
199             self._fp_bytes_read += len(data)
200 
201             try:
202                 if decode_content and self._decoder:
203                     data = self._decoder.decompress(data)
204             except (IOError, zlib.error) as e:
205                 raise DecodeError(
206                     "Received response with content-encoding: %s, but "
207                     "failed to decode it." % content_encoding,
208                     e)
209 
210             if flush_decoder and decode_content and self._decoder:
211                 buf = self._decoder.decompress(binary_type())
212                 data += buf + self._decoder.flush()
213 
214             if cache_content:
215                 self._body = data
216 
217             return data
218 
219         finally:
220             if self._original_response and self._original_response.isclosed():
221                 self.release_conn()
222 
223     def stream(self, amt=2**16, decode_content=None):
224         """
225         A generator wrapper for the read() method. A call will block until
226         ``amt`` bytes have been read from the connection or until the
227         connection is closed.
228 
229         :param amt:
230             How much of the content to read. The generator will return up to
231             much data per iteration, but may return less. This is particularly
232             likely when using compressed data. However, the empty string will
233             never be returned.
234 
235         :param decode_content:
236             If True, will attempt to decode the body based on the
237             'content-encoding' header.
238         """
239         while not is_fp_closed(self._fp):
240             data = self.read(amt=amt, decode_content=decode_content)
241 
242             if data:
243                 yield data
244 
245     @classmethod
246     def from_httplib(ResponseCls, r, **response_kw):
247         """
248         Given an :class:`httplib.HTTPResponse` instance ``r``, return a
249         corresponding :class:`urllib3.response.HTTPResponse` object.
250 
251         Remaining parameters are passed to the HTTPResponse constructor, along
252         with ``original_response=r``.
253         """
254 
255         headers = HTTPHeaderDict()
256         for k, v in r.getheaders():
257             headers.add(k, v)
258 
259         # HTTPResponse objects in Python 3 don't have a .strict attribute
260         strict = getattr(r, 'strict', 0)
261         return ResponseCls(body=r,
262                            headers=headers,
263                            status=r.status,
264                            version=r.version,
265                            reason=r.reason,
266                            strict=strict,
267                            original_response=r,
268                            **response_kw)
269 
270     # Backwards-compatibility methods for httplib.HTTPResponse
271     def getheaders(self):
272         return self.headers
273 
274     def getheader(self, name, default=None):
275         return self.headers.get(name, default)
276 
277     # Overrides from io.IOBase
278     def close(self):
279         if not self.closed:
280             self._fp.close()
281 
282     @property
283     def closed(self):
284         if self._fp is None:
285             return True
286         elif hasattr(self._fp, 'closed'):
287             return self._fp.closed
288         elif hasattr(self._fp, 'isclosed'):  # Python 2
289             return self._fp.isclosed()
290         else:
291             return True
292 
293     def fileno(self):
294         if self._fp is None:
295             raise IOError("HTTPResponse has no file to get a fileno from")
296         elif hasattr(self._fp, "fileno"):
297             return self._fp.fileno()
298         else:
299             raise IOError("The file-like object  this HTTPResponse is wrapped "
300                           "around has no file descriptor")
301 
302     def flush(self):
303         if self._fp is not None and hasattr(self._fp, 'flush'):
304             return self._fp.flush()
305 
306     def readable(self):
307         return True
308
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/urllib3/response.py b/urllib3/response.py
--- a/urllib3/response.py
+++ b/urllib3/response.py
@@ -5,19 +5,16 @@
 # the MIT License: http://www.opensource.org/licenses/mit-license.php
 
 
-import logging
 import zlib
 import io
+from socket import timeout as SocketTimeout
 
 from ._collections import HTTPHeaderDict
-from .exceptions import DecodeError
+from .exceptions import DecodeError, ReadTimeoutError
 from .packages.six import string_types as basestring, binary_type
 from .util import is_fp_closed
 
 
-log = logging.getLogger(__name__)
-
-
 class DeflateDecoder(object):
 
     def __init__(self):
@@ -178,23 +175,29 @@
         flush_decoder = False
 
         try:
-            if amt is None:
-                # cStringIO doesn't like amt=None
-                data = self._fp.read()
-                flush_decoder = True
-            else:
-                cache_content = False
-                data = self._fp.read(amt)
-                if amt != 0 and not data:  # Platform-specific: Buggy versions of Python.
-                    # Close the connection when no data is returned
-                    #
-                    # This is redundant to what httplib/http.client _should_
-                    # already do.  However, versions of python released before
-                    # December 15, 2012 (http://bugs.python.org/issue16298) do
-                    # not properly close the connection in all cases. There is
-                    # no harm in redundantly calling close.
-                    self._fp.close()
+            try:
+                if amt is None:
+                    # cStringIO doesn't like amt=None
+                    data = self._fp.read()
                     flush_decoder = True
+                else:
+                    cache_content = False
+                    data = self._fp.read(amt)
+                    if amt != 0 and not data:  # Platform-specific: Buggy versions of Python.
+                        # Close the connection when no data is returned
+                        #
+                        # This is redundant to what httplib/http.client _should_
+                        # already do.  However, versions of python released before
+                        # December 15, 2012 (http://bugs.python.org/issue16298) do
+                        # not properly close the connection in all cases. There is
+                        # no harm in redundantly calling close.
+                        self._fp.close()
+                        flush_decoder = True
+
+            except SocketTimeout:
+                # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but
+                # there is yet no clean way to get at it from this context.
+                raise ReadTimeoutError(self._pool, None, 'Read timed out.')
 
             self._fp_bytes_read += len(data)
 
@@ -204,8 +207,7 @@
             except (IOError, zlib.error) as e:
                 raise DecodeError(
                     "Received response with content-encoding: %s, but "
-                    "failed to decode it." % content_encoding,
-                    e)
+                    "failed to decode it." % content_encoding, e)
 
             if flush_decoder and decode_content and self._decoder:
                 buf = self._decoder.decompress(binary_type())
@@ -296,7 +298,7 @@
         elif hasattr(self._fp, "fileno"):
             return self._fp.fileno()
         else:
-            raise IOError("The file-like object  this HTTPResponse is wrapped "
+            raise IOError("The file-like object this HTTPResponse is wrapped "
                           "around has no file descriptor")
 
     def flush(self):

{"golden_diff": "diff --git a/urllib3/response.py b/urllib3/response.py\n--- a/urllib3/response.py\n+++ b/urllib3/response.py\n@@ -5,19 +5,16 @@\n # the MIT License: http://www.opensource.org/licenses/mit-license.php\n \n \n-import logging\n import zlib\n import io\n+from socket import timeout as SocketTimeout\n \n from ._collections import HTTPHeaderDict\n-from .exceptions import DecodeError\n+from .exceptions import DecodeError, ReadTimeoutError\n from .packages.six import string_types as basestring, binary_type\n from .util import is_fp_closed\n \n \n-log = logging.getLogger(__name__)\n-\n-\n class DeflateDecoder(object):\n \n     def __init__(self):\n@@ -178,23 +175,29 @@\n         flush_decoder = False\n \n         try:\n-            if amt is None:\n-                # cStringIO doesn't like amt=None\n-                data = self._fp.read()\n-                flush_decoder = True\n-            else:\n-                cache_content = False\n-                data = self._fp.read(amt)\n-                if amt != 0 and not data:  # Platform-specific: Buggy versions of Python.\n-                    # Close the connection when no data is returned\n-                    #\n-                    # This is redundant to what httplib/http.client _should_\n-                    # already do.  However, versions of python released before\n-                    # December 15, 2012 (http://bugs.python.org/issue16298) do\n-                    # not properly close the connection in all cases. There is\n-                    # no harm in redundantly calling close.\n-                    self._fp.close()\n+            try:\n+                if amt is None:\n+                    # cStringIO doesn't like amt=None\n+                    data = self._fp.read()\n                     flush_decoder = True\n+                else:\n+                    cache_content = False\n+                    data = self._fp.read(amt)\n+                    if amt != 0 and not data:  # Platform-specific: Buggy versions of Python.\n+                        # Close the connection when no data is returned\n+                        #\n+                        # This is redundant to what httplib/http.client _should_\n+                        # already do.  However, versions of python released before\n+                        # December 15, 2012 (http://bugs.python.org/issue16298) do\n+                        # not properly close the connection in all cases. There is\n+                        # no harm in redundantly calling close.\n+                        self._fp.close()\n+                        flush_decoder = True\n+\n+            except SocketTimeout:\n+                # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but\n+                # there is yet no clean way to get at it from this context.\n+                raise ReadTimeoutError(self._pool, None, 'Read timed out.')\n \n             self._fp_bytes_read += len(data)\n \n@@ -204,8 +207,7 @@\n             except (IOError, zlib.error) as e:\n                 raise DecodeError(\n                     \"Received response with content-encoding: %s, but \"\n-                    \"failed to decode it.\" % content_encoding,\n-                    e)\n+                    \"failed to decode it.\" % content_encoding, e)\n \n             if flush_decoder and decode_content and self._decoder:\n                 buf = self._decoder.decompress(binary_type())\n@@ -296,7 +298,7 @@\n         elif hasattr(self._fp, \"fileno\"):\n             return self._fp.fileno()\n         else:\n-            raise IOError(\"The file-like object  this HTTPResponse is wrapped \"\n+            raise IOError(\"The file-like object this HTTPResponse is wrapped \"\n                           \"around has no file descriptor\")\n \n     def flush(self):\n", "issue": "socket.timeout not wrapped properly\nAs mentioned in a [comment](https://github.com/kennethreitz/requests/issues/1787#issuecomment-30510686) on kennethreitz/requests#1787 urllib3 apparently lets a `socket.timeout` exception propagate outside library code instead of wrapping it e.g. with `urllib3.exceptions.TimeoutError`. See the linked issue for a full backtrace.\n\n", "before_files": [{"content": "# urllib3/response.py\n# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)\n#\n# This module is part of urllib3 and is released under\n# the MIT License: http://www.opensource.org/licenses/mit-license.php\n\n\nimport logging\nimport zlib\nimport io\n\nfrom ._collections import HTTPHeaderDict\nfrom .exceptions import DecodeError\nfrom .packages.six import string_types as basestring, binary_type\nfrom .util import is_fp_closed\n\n\nlog = logging.getLogger(__name__)\n\n\nclass DeflateDecoder(object):\n\n    def __init__(self):\n        self._first_try = True\n        self._data = binary_type()\n        self._obj = zlib.decompressobj()\n\n    def __getattr__(self, name):\n        return getattr(self._obj, name)\n\n    def decompress(self, data):\n        if not self._first_try:\n            return self._obj.decompress(data)\n\n        self._data += data\n        try:\n            return self._obj.decompress(data)\n        except zlib.error:\n            self._first_try = False\n            self._obj = zlib.decompressobj(-zlib.MAX_WBITS)\n            try:\n                return self.decompress(self._data)\n            finally:\n                self._data = None\n\n\ndef _get_decoder(mode):\n    if mode == 'gzip':\n        return zlib.decompressobj(16 + zlib.MAX_WBITS)\n\n    return DeflateDecoder()\n\n\nclass HTTPResponse(io.IOBase):\n    \"\"\"\n    HTTP Response container.\n\n    Backwards-compatible to httplib's HTTPResponse but the response ``body`` is\n    loaded and decoded on-demand when the ``data`` property is accessed.\n\n    Extra parameters for behaviour not present in httplib.HTTPResponse:\n\n    :param preload_content:\n        If True, the response's body will be preloaded during construction.\n\n    :param decode_content:\n        If True, attempts to decode specific content-encoding's based on headers\n        (like 'gzip' and 'deflate') will be skipped and raw data will be used\n        instead.\n\n    :param original_response:\n        When this HTTPResponse wrapper is generated from an httplib.HTTPResponse\n        object, it's convenient to include the original for debug purposes. It's\n        otherwise unused.\n    \"\"\"\n\n    CONTENT_DECODERS = ['gzip', 'deflate']\n    REDIRECT_STATUSES = [301, 302, 303, 307, 308]\n\n    def __init__(self, body='', headers=None, status=0, version=0, reason=None,\n                 strict=0, preload_content=True, decode_content=True,\n                 original_response=None, pool=None, connection=None):\n\n        self.headers = HTTPHeaderDict()\n        if headers:\n            self.headers.update(headers)\n        self.status = status\n        self.version = version\n        self.reason = reason\n        self.strict = strict\n        self.decode_content = decode_content\n\n        self._decoder = None\n        self._body = body if body and isinstance(body, basestring) else None\n        self._fp = None\n        self._original_response = original_response\n        self._fp_bytes_read = 0\n\n        self._pool = pool\n        self._connection = connection\n\n        if hasattr(body, 'read'):\n            self._fp = body\n\n        if preload_content and not self._body:\n            self._body = self.read(decode_content=decode_content)\n\n    def get_redirect_location(self):\n        \"\"\"\n        Should we redirect and where to?\n\n        :returns: Truthy redirect location string if we got a redirect status\n            code and valid location. ``None`` if redirect status and no\n            location. ``False`` if not a redirect status code.\n        \"\"\"\n        if self.status in self.REDIRECT_STATUSES:\n            return self.headers.get('location')\n\n        return False\n\n    def release_conn(self):\n        if not self._pool or not self._connection:\n            return\n\n        self._pool._put_conn(self._connection)\n        self._connection = None\n\n    @property\n    def data(self):\n        # For backwords-compat with earlier urllib3 0.4 and earlier.\n        if self._body:\n            return self._body\n\n        if self._fp:\n            return self.read(cache_content=True)\n\n    def tell(self):\n        \"\"\"\n        Obtain the number of bytes pulled over the wire so far. May differ from\n        the amount of content returned by :meth:``HTTPResponse.read`` if bytes\n        are encoded on the wire (e.g, compressed).\n        \"\"\"\n        return self._fp_bytes_read\n\n    def read(self, amt=None, decode_content=None, cache_content=False):\n        \"\"\"\n        Similar to :meth:`httplib.HTTPResponse.read`, but with two additional\n        parameters: ``decode_content`` and ``cache_content``.\n\n        :param amt:\n            How much of the content to read. If specified, caching is skipped\n            because it doesn't make sense to cache partial content as the full\n            response.\n\n        :param decode_content:\n            If True, will attempt to decode the body based on the\n            'content-encoding' header.\n\n        :param cache_content:\n            If True, will save the returned data such that the same result is\n            returned despite of the state of the underlying file object. This\n            is useful if you want the ``.data`` property to continue working\n            after having ``.read()`` the file object. (Overridden if ``amt`` is\n            set.)\n        \"\"\"\n        # Note: content-encoding value should be case-insensitive, per RFC 2616\n        # Section 3.5\n        content_encoding = self.headers.get('content-encoding', '').lower()\n        if self._decoder is None:\n            if content_encoding in self.CONTENT_DECODERS:\n                self._decoder = _get_decoder(content_encoding)\n        if decode_content is None:\n            decode_content = self.decode_content\n\n        if self._fp is None:\n            return\n\n        flush_decoder = False\n\n        try:\n            if amt is None:\n                # cStringIO doesn't like amt=None\n                data = self._fp.read()\n                flush_decoder = True\n            else:\n                cache_content = False\n                data = self._fp.read(amt)\n                if amt != 0 and not data:  # Platform-specific: Buggy versions of Python.\n                    # Close the connection when no data is returned\n                    #\n                    # This is redundant to what httplib/http.client _should_\n                    # already do.  However, versions of python released before\n                    # December 15, 2012 (http://bugs.python.org/issue16298) do\n                    # not properly close the connection in all cases. There is\n                    # no harm in redundantly calling close.\n                    self._fp.close()\n                    flush_decoder = True\n\n            self._fp_bytes_read += len(data)\n\n            try:\n                if decode_content and self._decoder:\n                    data = self._decoder.decompress(data)\n            except (IOError, zlib.error) as e:\n                raise DecodeError(\n                    \"Received response with content-encoding: %s, but \"\n                    \"failed to decode it.\" % content_encoding,\n                    e)\n\n            if flush_decoder and decode_content and self._decoder:\n                buf = self._decoder.decompress(binary_type())\n                data += buf + self._decoder.flush()\n\n            if cache_content:\n                self._body = data\n\n            return data\n\n        finally:\n            if self._original_response and self._original_response.isclosed():\n                self.release_conn()\n\n    def stream(self, amt=2**16, decode_content=None):\n        \"\"\"\n        A generator wrapper for the read() method. A call will block until\n        ``amt`` bytes have been read from the connection or until the\n        connection is closed.\n\n        :param amt:\n            How much of the content to read. The generator will return up to\n            much data per iteration, but may return less. This is particularly\n            likely when using compressed data. However, the empty string will\n            never be returned.\n\n        :param decode_content:\n            If True, will attempt to decode the body based on the\n            'content-encoding' header.\n        \"\"\"\n        while not is_fp_closed(self._fp):\n            data = self.read(amt=amt, decode_content=decode_content)\n\n            if data:\n                yield data\n\n    @classmethod\n    def from_httplib(ResponseCls, r, **response_kw):\n        \"\"\"\n        Given an :class:`httplib.HTTPResponse` instance ``r``, return a\n        corresponding :class:`urllib3.response.HTTPResponse` object.\n\n        Remaining parameters are passed to the HTTPResponse constructor, along\n        with ``original_response=r``.\n        \"\"\"\n\n        headers = HTTPHeaderDict()\n        for k, v in r.getheaders():\n            headers.add(k, v)\n\n        # HTTPResponse objects in Python 3 don't have a .strict attribute\n        strict = getattr(r, 'strict', 0)\n        return ResponseCls(body=r,\n                           headers=headers,\n                           status=r.status,\n                           version=r.version,\n                           reason=r.reason,\n                           strict=strict,\n                           original_response=r,\n                           **response_kw)\n\n    # Backwards-compatibility methods for httplib.HTTPResponse\n    def getheaders(self):\n        return self.headers\n\n    def getheader(self, name, default=None):\n        return self.headers.get(name, default)\n\n    # Overrides from io.IOBase\n    def close(self):\n        if not self.closed:\n            self._fp.close()\n\n    @property\n    def closed(self):\n        if self._fp is None:\n            return True\n        elif hasattr(self._fp, 'closed'):\n            return self._fp.closed\n        elif hasattr(self._fp, 'isclosed'):  # Python 2\n            return self._fp.isclosed()\n        else:\n            return True\n\n    def fileno(self):\n        if self._fp is None:\n            raise IOError(\"HTTPResponse has no file to get a fileno from\")\n        elif hasattr(self._fp, \"fileno\"):\n            return self._fp.fileno()\n        else:\n            raise IOError(\"The file-like object  this HTTPResponse is wrapped \"\n                          \"around has no file descriptor\")\n\n    def flush(self):\n        if self._fp is not None and hasattr(self._fp, 'flush'):\n            return self._fp.flush()\n\n    def readable(self):\n        return True\n", "path": "urllib3/response.py"}], "after_files": [{"content": "# urllib3/response.py\n# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)\n#\n# This module is part of urllib3 and is released under\n# the MIT License: http://www.opensource.org/licenses/mit-license.php\n\n\nimport zlib\nimport io\nfrom socket import timeout as SocketTimeout\n\nfrom ._collections import HTTPHeaderDict\nfrom .exceptions import DecodeError, ReadTimeoutError\nfrom .packages.six import string_types as basestring, binary_type\nfrom .util import is_fp_closed\n\n\nclass DeflateDecoder(object):\n\n    def __init__(self):\n        self._first_try = True\n        self._data = binary_type()\n        self._obj = zlib.decompressobj()\n\n    def __getattr__(self, name):\n        return getattr(self._obj, name)\n\n    def decompress(self, data):\n        if not self._first_try:\n            return self._obj.decompress(data)\n\n        self._data += data\n        try:\n            return self._obj.decompress(data)\n        except zlib.error:\n            self._first_try = False\n            self._obj = zlib.decompressobj(-zlib.MAX_WBITS)\n            try:\n                return self.decompress(self._data)\n            finally:\n                self._data = None\n\n\ndef _get_decoder(mode):\n    if mode == 'gzip':\n        return zlib.decompressobj(16 + zlib.MAX_WBITS)\n\n    return DeflateDecoder()\n\n\nclass HTTPResponse(io.IOBase):\n    \"\"\"\n    HTTP Response container.\n\n    Backwards-compatible to httplib's HTTPResponse but the response ``body`` is\n    loaded and decoded on-demand when the ``data`` property is accessed.\n\n    Extra parameters for behaviour not present in httplib.HTTPResponse:\n\n    :param preload_content:\n        If True, the response's body will be preloaded during construction.\n\n    :param decode_content:\n        If True, attempts to decode specific content-encoding's based on headers\n        (like 'gzip' and 'deflate') will be skipped and raw data will be used\n        instead.\n\n    :param original_response:\n        When this HTTPResponse wrapper is generated from an httplib.HTTPResponse\n        object, it's convenient to include the original for debug purposes. It's\n        otherwise unused.\n    \"\"\"\n\n    CONTENT_DECODERS = ['gzip', 'deflate']\n    REDIRECT_STATUSES = [301, 302, 303, 307, 308]\n\n    def __init__(self, body='', headers=None, status=0, version=0, reason=None,\n                 strict=0, preload_content=True, decode_content=True,\n                 original_response=None, pool=None, connection=None):\n\n        self.headers = HTTPHeaderDict()\n        if headers:\n            self.headers.update(headers)\n        self.status = status\n        self.version = version\n        self.reason = reason\n        self.strict = strict\n        self.decode_content = decode_content\n\n        self._decoder = None\n        self._body = body if body and isinstance(body, basestring) else None\n        self._fp = None\n        self._original_response = original_response\n        self._fp_bytes_read = 0\n\n        self._pool = pool\n        self._connection = connection\n\n        if hasattr(body, 'read'):\n            self._fp = body\n\n        if preload_content and not self._body:\n            self._body = self.read(decode_content=decode_content)\n\n    def get_redirect_location(self):\n        \"\"\"\n        Should we redirect and where to?\n\n        :returns: Truthy redirect location string if we got a redirect status\n            code and valid location. ``None`` if redirect status and no\n            location. ``False`` if not a redirect status code.\n        \"\"\"\n        if self.status in self.REDIRECT_STATUSES:\n            return self.headers.get('location')\n\n        return False\n\n    def release_conn(self):\n        if not self._pool or not self._connection:\n            return\n\n        self._pool._put_conn(self._connection)\n        self._connection = None\n\n    @property\n    def data(self):\n        # For backwords-compat with earlier urllib3 0.4 and earlier.\n        if self._body:\n            return self._body\n\n        if self._fp:\n            return self.read(cache_content=True)\n\n    def tell(self):\n        \"\"\"\n        Obtain the number of bytes pulled over the wire so far. May differ from\n        the amount of content returned by :meth:``HTTPResponse.read`` if bytes\n        are encoded on the wire (e.g, compressed).\n        \"\"\"\n        return self._fp_bytes_read\n\n    def read(self, amt=None, decode_content=None, cache_content=False):\n        \"\"\"\n        Similar to :meth:`httplib.HTTPResponse.read`, but with two additional\n        parameters: ``decode_content`` and ``cache_content``.\n\n        :param amt:\n            How much of the content to read. If specified, caching is skipped\n            because it doesn't make sense to cache partial content as the full\n            response.\n\n        :param decode_content:\n            If True, will attempt to decode the body based on the\n            'content-encoding' header.\n\n        :param cache_content:\n            If True, will save the returned data such that the same result is\n            returned despite of the state of the underlying file object. This\n            is useful if you want the ``.data`` property to continue working\n            after having ``.read()`` the file object. (Overridden if ``amt`` is\n            set.)\n        \"\"\"\n        # Note: content-encoding value should be case-insensitive, per RFC 2616\n        # Section 3.5\n        content_encoding = self.headers.get('content-encoding', '').lower()\n        if self._decoder is None:\n            if content_encoding in self.CONTENT_DECODERS:\n                self._decoder = _get_decoder(content_encoding)\n        if decode_content is None:\n            decode_content = self.decode_content\n\n        if self._fp is None:\n            return\n\n        flush_decoder = False\n\n        try:\n            try:\n                if amt is None:\n                    # cStringIO doesn't like amt=None\n                    data = self._fp.read()\n                    flush_decoder = True\n                else:\n                    cache_content = False\n                    data = self._fp.read(amt)\n                    if amt != 0 and not data:  # Platform-specific: Buggy versions of Python.\n                        # Close the connection when no data is returned\n                        #\n                        # This is redundant to what httplib/http.client _should_\n                        # already do.  However, versions of python released before\n                        # December 15, 2012 (http://bugs.python.org/issue16298) do\n                        # not properly close the connection in all cases. There is\n                        # no harm in redundantly calling close.\n                        self._fp.close()\n                        flush_decoder = True\n\n            except SocketTimeout:\n                # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but\n                # there is yet no clean way to get at it from this context.\n                raise ReadTimeoutError(self._pool, None, 'Read timed out.')\n\n            self._fp_bytes_read += len(data)\n\n            try:\n                if decode_content and self._decoder:\n                    data = self._decoder.decompress(data)\n            except (IOError, zlib.error) as e:\n                raise DecodeError(\n                    \"Received response with content-encoding: %s, but \"\n                    \"failed to decode it.\" % content_encoding, e)\n\n            if flush_decoder and decode_content and self._decoder:\n                buf = self._decoder.decompress(binary_type())\n                data += buf + self._decoder.flush()\n\n            if cache_content:\n                self._body = data\n\n            return data\n\n        finally:\n            if self._original_response and self._original_response.isclosed():\n                self.release_conn()\n\n    def stream(self, amt=2**16, decode_content=None):\n        \"\"\"\n        A generator wrapper for the read() method. A call will block until\n        ``amt`` bytes have been read from the connection or until the\n        connection is closed.\n\n        :param amt:\n            How much of the content to read. The generator will return up to\n            much data per iteration, but may return less. This is particularly\n            likely when using compressed data. However, the empty string will\n            never be returned.\n\n        :param decode_content:\n            If True, will attempt to decode the body based on the\n            'content-encoding' header.\n        \"\"\"\n        while not is_fp_closed(self._fp):\n            data = self.read(amt=amt, decode_content=decode_content)\n\n            if data:\n                yield data\n\n    @classmethod\n    def from_httplib(ResponseCls, r, **response_kw):\n        \"\"\"\n        Given an :class:`httplib.HTTPResponse` instance ``r``, return a\n        corresponding :class:`urllib3.response.HTTPResponse` object.\n\n        Remaining parameters are passed to the HTTPResponse constructor, along\n        with ``original_response=r``.\n        \"\"\"\n\n        headers = HTTPHeaderDict()\n        for k, v in r.getheaders():\n            headers.add(k, v)\n\n        # HTTPResponse objects in Python 3 don't have a .strict attribute\n        strict = getattr(r, 'strict', 0)\n        return ResponseCls(body=r,\n                           headers=headers,\n                           status=r.status,\n                           version=r.version,\n                           reason=r.reason,\n                           strict=strict,\n                           original_response=r,\n                           **response_kw)\n\n    # Backwards-compatibility methods for httplib.HTTPResponse\n    def getheaders(self):\n        return self.headers\n\n    def getheader(self, name, default=None):\n        return self.headers.get(name, default)\n\n    # Overrides from io.IOBase\n    def close(self):\n        if not self.closed:\n            self._fp.close()\n\n    @property\n    def closed(self):\n        if self._fp is None:\n            return True\n        elif hasattr(self._fp, 'closed'):\n            return self._fp.closed\n        elif hasattr(self._fp, 'isclosed'):  # Python 2\n            return self._fp.isclosed()\n        else:\n            return True\n\n    def fileno(self):\n        if self._fp is None:\n            raise IOError(\"HTTPResponse has no file to get a fileno from\")\n        elif hasattr(self._fp, \"fileno\"):\n            return self._fp.fileno()\n        else:\n            raise IOError(\"The file-like object this HTTPResponse is wrapped \"\n                          \"around has no file descriptor\")\n\n    def flush(self):\n        if self._fp is not None and hasattr(self._fp, 'flush'):\n            return self._fp.flush()\n\n    def readable(self):\n        return True\n", "path": "urllib3/response.py"}]}