Merge remote-tracking branch 'origin/master'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 74609c5, a693753 · Browse files · 21 files·+475 added−204 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
21 files+475 added−204 removed
- other:+475 added−204 removed
Provenance
- Commit
8686255- Tree
b1f04b7- Author
Kenneth Reitz <me@kennethreitz.org>- Committer
Kenneth Reitz <me@kennethreitz.org>- Parent 1
74609c5- Parent 2
a693753
21 files changed+475 added−204 removed
modified:docs/community/out-there.rst+1 added
28 unmodified lines29 - `My 'Python for Humans' talk <http://python-for-humans.heroku.com>`_ ( `audio <http://codeconf.s3.amazonaws.com/2011/pycodeconf/talks/PyCodeConf2011%20-%20Kenneth%20Reitz.m4a>`_ )30 - `Issac Kelly's 'Consuming Web APIs' talk <http://issackelly.github.com/Consuming-Web-APIs-with-Python-Talk/slides/slides.html>`_31 - `Blog post about Requests via Yum <http://arunsag.wordpress.com/2011/08/17/new-package-python-requests-http-for-humans/>`_32 - `Russian blog post introducing Requests <http://habrahabr.ru/blogs/python/126262/>`_33+- `Sending JSON in Requests <http://www.coglib.com/~icordasc/blog/2014/11/sending-json-in-requests.html>`_modified:docs/community/recommended.rst+12 added
41 unmodified lines42 to provide authentication. It also provides a lot of tweaks that handle ways43 that specific OAuth providers differ from the standard specifications.44 45 .. _requests-oauthlib: https://requests-oauthlib.readthedocs.org/en/latest/46+47+48+Betamax49+-------50+51+`Betamax`_ records your HTTP interactions so the NSA does not have to.52+A VCR imitation designed only for Python-Requests.53+54+.. _betamax: https://github.com/sigmavirus24/betamax55+56+57+added:docs/community/release-process.rst+54 added
1+Release Process and Rules2+=========================3+4+.. versionadded:: v2.6.25+6+Starting with the version to be released after ``v2.6.2``, the following rules7+will govern and describe how the Requests core team produces a new release.8+9+Major Releases10+--------------11+12+A major release will include breaking changes. When it is versioned, it will13+be versioned as ``vX.0.0``. For example, if the previous release was14+``v10.2.7`` the next version will be ``v11.0.0``.15+16+Breaking changes are changes that break backwards compatibility with prior17+versions. If the project were to change the ``text`` attribute on a18+``Response`` object to a method, that would only happen in a Major release.19+20+Major releases may also include miscellaneous bug fixes and upgrades to21+vendored packages. The core developers of Requests are committed to providing22+a good user experience. This means we're also committed to preserving23+backwards compatibility as much as possible. Major releases will be infrequent24+and will need strong justifications before they are considered.25+26+Minor Releases27+--------------28+29+A minor release will not include breaking changes but may include30+miscellaneous bug fixes and upgrades to vendored packages. If the previous31+version of Requests released was ``v10.2.7`` a minor release would be32+versioned as ``v10.3.0``.33+34+Minor releases will be backwards compatible with releases that have the same35+major version number. In other words, all versions that would start with36+``v10.`` should be compatible with each other.37+38+Hotfix Releases39+---------------40+41+A hotfix release will only include bug fixes that were missed when the project42+released the previous version. If the previous version of Requests released43+``v10.2.7`` the hotfix release would be versioned as ``v10.2.8``.44+45+Hotfixes will **not** include upgrades to vendored dependences after46+``v2.6.2``47+48+Reasoning49+---------50+51+In the 2.5 and 2.6 release series, the Requests core team upgraded vendored52+dependencies and caused a great deal of headaches for both users and the core53+team. To reduce this pain, we're forming a concrete set of procedures so54+expectations will be properly set.modified:docs/community/updates.rst+3 added-14 removed
1 .. _updates:2 3 4-5-4 Community Updates5 =================6 7 If you'd like to stay up to date on the community and development of Requests,8 unmodified lines16 17 Twitter18 -------19 22-I often tweet about new features and releases of Requests.20+The author, Kenneth Reitz, often tweets about new features and releases of Requests.21 22 Follow `@kennethreitz <https://twitter.com/kennethreitz>`_ for updates.23 24 27-Mailing List28-------------25 30-There's a low-volume mailing list for Requests. To subscribe to the31-mailing list, send an email to32-`requests@librelist.org <mailto:requests@librelist.org>`_.26+Release and Version History27+===========================28 34-35-36-37-Software Updates38-================39-29 .. include:: ../../HISTORY.rst30 added:docs/dev/contributing.rst+145 added
1+.. _contributing:2+3+Contributor's Guide4+===================5+6+If you're reading this you're probably interested in contributing to7+Requests. First, We'd like to say: thank you! Open source projects8+live-and-die based on the support they receive from others, and the fact that9+you're even considering supporting Requests is very generous of10+you.11+12+This document lays out guidelines and advice for contributing to Requests.13+If you're thinking of contributing, start by reading this thoroughly and14+getting a feel for how contributing to the project works. If you have any15+questions, feel free to reach out to either `Ian Cordasco`_ or `Cory Benfield`_,16+the primary maintainers.17+18+The guide is split into sections based on the type of contribution you're19+thinking of making, with a section that covers general guidelines for all20+contributors.21+22+.. _Ian Cordasco: http://www.coglib.com/~icordasc/23+.. _Cory Benfield: https://lukasa.co.uk/about24+25+26+All Contributions27+-----------------28+29+Be Cordial30+~~~~~~~~~~31+32+**Be cordial or be on your way.**33+34+Requests has one very important rule governing all forms of contribution,35+including reporting bugs or requesting features. This golden rule is36+`be cordial or be on your way`_. **All contributions are welcome**, as long as37+everyone involved is treated with respect.38+39+.. _be cordial or be on your way: http://kennethreitz.org/be-cordial-or-be-on-your-way/40+41+.. _early-feedback:42+43+Get Early Feedback44+~~~~~~~~~~~~~~~~~~45+46+If you are contributing, do not feel the need to sit on your contribution until47+it is perfectly polished and complete. It helps everyone involved for you to48+seek feedback as early as you possibly can. Submitting an early, unfinished49+version of your contribution for feedback in no way prejudices your chances of50+getting that contribution accepted, and can save you from putting a lot of work51+into a contribution that is not suitable for the project.52+53+Contribution Suitability54+~~~~~~~~~~~~~~~~~~~~~~~~55+56+The project maintainer has the last word on whether or not a contribution is57+suitable for Requests. All contributions will be considered, but from time58+to time contributions will be rejected because they do not suit the project.59+60+If your contribution is rejected, don't despair! So long as you followed these61+guidelines, you'll have a much better chance of getting your next contribution62+accepted.63+64+65+Code Contributions66+------------------67+68+Steps69+~~~~~70+71+When contributing code, you'll want to follow this checklist:72+73+1. Fork the repository on GitHub.74+2. Run the tests to confirm they all pass on your system. If they don't, you'll75+ need to investigate why they fail. If you're unable to diagnose this76+ yourself, raise it as a bug report by following the guidelines in this77+ document: :ref:`bug-reports`.78+3. Write tests that demonstrate your bug or feature. Ensure that they fail.79+4. Make your change.80+5. Run the entire test suite again, confirming that all tests pass *including81+ the ones you just added*.82+6. Send a GitHub Pull Request to the main repository's ``master`` branch.83+ GitHub Pull Requests are the expected method of code collaboration on this84+ project.85+86+The following sub-sections go into more detail on some of the points above.87+88+Code Review89+~~~~~~~~~~~90+91+Contributions will not be merged until they've been code reviewed. You should92+implement any code review feedback unless you strongly object to it. In the93+event that you object to the code review feedback, you should make your case94+clearly and calmly. If, after doing so, the feedback is judged to still apply,95+you must either apply the feedback or withdraw your contribution.96+97+New Contributors98+~~~~~~~~~~~~~~~~99+100+If you are new or relatively new to Open Source, welcome! Requests aims to101+be a gentle introduction to the world of Open Source. If you're concerned about102+how best to contribute, please consider mailing a maintainer (listed above) and103+asking for help.104+105+Please also check the :ref:`early-feedback` section.106+107+Documentation Contributions108+---------------------------109+110+Documentation improvements are always welcome! The documentation files live in111+the ``docs/`` directory of the codebase. They're written in112+`reStructuredText`_, and use `Sphinx`_ to generate the full suite of113+documentation.114+115+When contributing documentation, please attempt to follow the style of the116+documentation files. This means a soft-limit of 79 characters wide in your text117+files and a semi-formal prose style.118+119+.. _reStructuredText: http://docutils.sourceforge.net/rst.html120+.. _Sphinx: http://sphinx-doc.org/index.html121+122+123+.. _bug-reports:124+125+Bug Reports126+-----------127+128+Bug reports are hugely important! Before you raise one, though, please check129+through the `GitHub issues`_, **both open and closed**, to confirm that the bug130+hasn't been reported before. Duplicate bug reports are a huge drain on the time131+of other contributors, and should be avoided as much as possible.132+133+.. _GitHub issues: https://github.com/kennethreitz/requests/issues134+135+136+Feature Requests137+----------------138+139+Requests is in a perpeptual feature freeze. The maintainers believe that140+requests contains every major feature currently required by the vast majority141+of users.142+143+If you believe there is a feature missing, feel free to raise a feature144+request, but please do be aware that the overwhelming likelihood is that your145+feature request will not be accepted.modified:docs/index.rst+3 added-1 removed
113 unmodified lines114 :maxdepth: 1115 116 community/faq117 community/recommended118- community/out-there.rst118+ community/out-there119 community/support120 community/vulnerabilities121 community/updates122+ community/release-process123 124 API Documentation125 -----------------126 14 unmodified lines141 142 .. toctree::143 :maxdepth: 1144 145+ dev/contributing146 dev/philosophy147 dev/todo148 dev/authorsmodified:requests/packages/urllib3/contrib/pyopenssl.py+4 added-19 removed
36 unmodified lines37 Module Variables38 ----------------39 40 :var DEFAULT_SSL_CIPHER_LIST: The list of supported SSL/TLS cipher suites.41- Default: ``ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:42- ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS``41 42 .. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication43 .. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)44 37 unmodified lines82 ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER83 + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,84 }85 88-# A secure default.89-# Sources for more information on TLS ciphers:90-#91-# - https://wiki.mozilla.org/Security/Server_Side_TLS92-# - https://www.ssllabs.com/projects/best-practices/index.html93-# - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/94-#95-# The general intent is:96-# - Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),97-# - prefer ECDHE over DHE for better performance,98-# - prefer any AES-GCM over any AES-CBC for better performance and security,99-# - use 3DES as fallback which is secure but slow,100-# - disable NULL authentication, MD5 MACs and DSS for security reasons.101-DEFAULT_SSL_CIPHER_LIST = "ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:" + \102- "ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:" + \103- "!aNULL:!MD5:!DSS"86+DEFAULT_SSL_CIPHER_LIST = util.ssl_.DEFAULT_CIPHERS87 88 89 orig_util_HAS_SNI = util.HAS_SNI90 orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket190 unmodified lines281 while True:282 try:283 cnx.do_handshake()284 except OpenSSL.SSL.WantReadError:302- select.select([sock], [], [])285+ rd, _, _ = select.select([sock], [], [], sock.gettimeout())286+ if not rd:287+ raise timeout('select timed out')288 continue289 except OpenSSL.SSL.Error as e:290 raise ssl.SSLError('bad handshake', e)291 break2 unmodified linesmodified:requests/packages/urllib3/util/ssl_.py+26 added-12 removed
7 unmodified lines8 HAS_SNI = False9 create_default_context = None10 11 import errno12-import ssl12 import warnings13 14 try: # Test for SSL features15+ import ssl16 from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv2317 from ssl import HAS_SNI # Has SNI?18 except ImportError:19 pass4 unmodified lines24 except ImportError:25 OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x200000026 OP_NO_COMPRESSION = 0x2000027 28+# A secure default.29+# Sources for more information on TLS ciphers:30+#31+# - https://wiki.mozilla.org/Security/Server_Side_TLS32+# - https://www.ssllabs.com/projects/best-practices/index.html33+# - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/34+#35+# The general intent is:36+# - Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),37+# - prefer ECDHE over DHE for better performance,28-try:29- from ssl import _DEFAULT_CIPHERS30-except ImportError:31- _DEFAULT_CIPHERS = (32- 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'33- 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'34- '!eNULL:!MD5'35- )38+# - prefer any AES-GCM over any AES-CBC for better performance and security,39+# - use 3DES as fallback which is secure but slow,40+# - disable NULL authentication, MD5 MACs and DSS for security reasons.41+DEFAULT_CIPHERS = (42+ 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'43+ 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'44+ '!eNULL:!MD5'45+)46 47 try:48 from ssl import SSLContext # Modern SSL?49 except ImportError:50 import sys51 52 class SSLContext(object): # Platform-specific: Python 2 & 3.143- supports_set_ciphers = sys.version_info >= (2, 7)53+ supports_set_ciphers = ((2, 7) <= sys.version_info < (3,) or54+ (3, 2) <= sys.version_info)55 56 def __init__(self, protocol_version):57 self.protocol = protocol_version58 # Use default values from a real SSLContext118 unmodified lines177 178 return candidate179 180 170-def create_urllib3_context(ssl_version=None, cert_reqs=ssl.CERT_REQUIRED,181+def create_urllib3_context(ssl_version=None, cert_reqs=None,182 options=None, ciphers=None):183 """All arguments have the same meaning as ``ssl_wrap_socket``.184 185 By default, this function does a lot of the same work that28 unmodified lines214 :rtype: SSLContext215 """216 context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)217 218+ # Setting the default here, as we may have no ssl module on import219+ cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs220+221 if options is None:222 options = 0223 # SSLv2 is easily broken and is considered harmful and dangerous224 options |= OP_NO_SSLv25 unmodified lines230 231 context.options |= options232 233 if getattr(context, 'supports_set_ciphers', True): # Platform-specific: Python 2.6220- context.set_ciphers(ciphers or _DEFAULT_CIPHERS)234+ context.set_ciphers(ciphers or DEFAULT_CIPHERS)235 236 context.verify_mode = cert_reqs237 if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2238 # We do our own verification, including fingerprints and alternative42 unmodified linesmodified:requests/packages/urllib3/util/url.py+2 added
13 unmodified lines14 slots = ()15 16 def __new__(cls, scheme=None, auth=None, host=None, port=None, path=None,17 query=None, fragment=None):18+ if path and not path.startswith('/'):19+ path = '/' + path20 return super(Url, cls).__new__(cls, scheme, auth, host, port, path,21 query, fragment)22 23 @property191 unmodified linesmodified:requests/packages/urllib3/__init__.py+6 added-3 removed
2 unmodified lines3 """4 5 __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'6 __license__ = 'MIT'7-__version__ = '1.10.2'7+__version__ = '1.10.4'8 9 10 from .connectionpool import (11 HTTPConnectionPool,42 unmodified lines54 # ... Clean up.55 del NullHandler56 57 58-# Set security warning to always go off by default.58 import warnings59+# SecurityWarning's always go off by default.60-warnings.simplefilter('always', exceptions.SecurityWarning)60+warnings.simplefilter('always', exceptions.SecurityWarning, append=True)61+# InsecurePlatformWarning's don't vary between requests, so we keep it default.62+warnings.simplefilter('default', exceptions.InsecurePlatformWarning,63+ append=True)64 65 def disable_warnings(category=exceptions.HTTPWarning):66 """67 Helper for quickly disabling all urllib3 warnings.2 unmodified linesmodified:requests/packages/urllib3/_collections.py+24 added-21 removed
225 unmodified lines226 # vals should be a tuple then, i.e. only one item so far227 # Need to convert the tuple to list for further extension228 _dict_setitem(self, key_lower, [vals[0], vals[1], val])229 230- def extend(*args, **kwargs):230+ def extend(self, *args, **kwargs):231 """Generic import function for any type of header-like object.232 Adapted version of MutableMapping.update in order to insert items233 with self.add instead of self.__setitem__234 """235- if len(args) > 2:236- raise TypeError("update() takes at most 2 positional "235+ if len(args) > 1:236+ raise TypeError("extend() takes at most 1 positional "237 "arguments ({} given)".format(len(args)))238- elif not args:239- raise TypeError("update() takes at least 1 argument (0 given)")240- self = args[0]241- other = args[1] if len(args) >= 2 else ()238+ other = args[0] if len(args) >= 1 else ()239 243- if isinstance(other, Mapping):240+ if isinstance(other, HTTPHeaderDict):241+ for key, val in other.iteritems():242+ self.add(key, val)243+ elif isinstance(other, Mapping):244 for key in other:245 self.add(key, other[key])246 elif hasattr(other, "keys"):247 for key in other.keys():55 unmodified lines303 def items(self):304 return list(self.iteritems())305 306 @classmethod307- def from_httplib(cls, message, duplicates=('set-cookie',)): # Python 2307+ def from_httplib(cls, message): # Python 2308 """Read headers from a Python 2 httplib message object."""309- ret = cls(message.items())310- # ret now contains only the last header line for each duplicate.311- # Importing with all duplicates would be nice, but this would312- # mean to repeat most of the raw parsing already done, when the313- # message object was created. Extracting only the headers of interest 314- # separately, the cookies, should be faster and requires less315- # extra code.316- for key in duplicates:317- ret.discard(key)318- for val in message.getheaders(key):319- ret.add(key, val)320- return ret309+ # python2.7 does not expose a proper API for exporting multiheaders310+ # efficiently. This function re-reads raw lines from the message 311+ # object and extracts the multiheaders properly.312+ headers = []313+ 314+ for line in message.headers:315+ if line.startswith((' ', '\t')):316+ key, value = headers[-1]317+ headers[-1] = (key, value + '\r\n' + line.rstrip())318+ continue319+ 320+ key, value = line.split(':', 1)321+ headers.append((key, value.strip()))322+323+ return cls(headers)modified:requests/packages/urllib3/connection.py+2 added
258 unmodified lines259 if ssl:260 # Make a copy for testing.261 UnverifiedHTTPSConnection = HTTPSConnection262 HTTPSConnection = VerifiedHTTPSConnection263+else:264+ HTTPSConnection = DummyConnectionmodified:requests/packages/urllib3/connectionpool.py-1 removed
733 unmodified lines734 log.info("Starting new HTTPS connection (%d): %s"735 % (self.num_connections, self.host))736 737 if not self.ConnectionCls or self.ConnectionCls is DummyConnection:738- # Platform-specific: Python without ssl738 raise SSLError("Can't connect to HTTPS URL because the SSL "739 "module is not available.")740 741 actual_host = self.host54 unmodified linesmodified:requests/packages/urllib3/exceptions.py+5 added
160 unmodified lines161 162 class InsecurePlatformWarning(SecurityWarning):163 "Warned when certain SSL configuration is not available on a platform."164 pass165+166+167+class ResponseNotChunked(ProtocolError, ValueError):168+ "Response needs to be chunked in order to read it as chunks."169+ passmodified:requests/packages/urllib3/response.py+136 added-23 removed
1+try:2+ import http.client as httplib3+except ImportError:4+ import httplib5 import zlib6 import io7 from socket import timeout as SocketTimeout8 9 from ._collections import HTTPHeaderDict6-from .exceptions import ProtocolError, DecodeError, ReadTimeoutError10+from .exceptions import (11+ ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked12+)13 from .packages.six import string_types as basestring, binary_type, PY314 from .connection import HTTPException, BaseSSLError15 from .util.response import is_fp_closed16 105 unmodified lines122 123 if hasattr(body, 'read'):124 self._fp = body125 126+ # Are we using the chunked-style of transfer encoding?127+ self.chunked = False128+ self.chunk_left = None129+ tr_enc = self.headers.get('transfer-encoding', '').lower()130+ # Don't incur the penalty of creating a list and then discarding it131+ encodings = (enc.strip() for enc in tr_enc.split(","))132+ if "chunked" in encodings:133+ self.chunked = True134+135+ # We certainly don't want to preload content when the response is chunked.120- if preload_content and not self._body:136+ if not self.chunked and preload_content and not self._body:137 self._body = self.read(decode_content=decode_content)138 139 def get_redirect_location(self):140 """31 unmodified lines172 are encoded on the wire (e.g, compressed).173 """174 return self._fp_bytes_read175 176+ def _init_decoder(self):177+ """178+ Set-up the _decoder attribute if necessar.179+ """180+ # Note: content-encoding value should be case-insensitive, per RFC 7230181+ # Section 3.2182+ content_encoding = self.headers.get('content-encoding', '').lower()183+ if self._decoder is None and content_encoding in self.CONTENT_DECODERS:184+ self._decoder = _get_decoder(content_encoding)185+186+ def _decode(self, data, decode_content, flush_decoder):187+ """188+ Decode the data passed in and potentially flush the decoder.189+ """190+ try:191+ if decode_content and self._decoder:192+ data = self._decoder.decompress(data)193+ except (IOError, zlib.error) as e:194+ content_encoding = self.headers.get('content-encoding', '').lower()195+ raise DecodeError(196+ "Received response with content-encoding: %s, but "197+ "failed to decode it." % content_encoding, e)198+199+ if flush_decoder and decode_content and self._decoder:200+ buf = self._decoder.decompress(binary_type())201+ data += buf + self._decoder.flush()202+203+ return data204+205 def read(self, amt=None, decode_content=None, cache_content=False):206 """207 Similar to :meth:`httplib.HTTPResponse.read`, but with two additional208 parameters: ``decode_content`` and ``cache_content``.13 unmodified lines222 is useful if you want the ``.data`` property to continue working223 after having ``.read()`` the file object. (Overridden if ``amt`` is224 set.)225 """181- # Note: content-encoding value should be case-insensitive, per RFC 7230182- # Section 3.2183- content_encoding = self.headers.get('content-encoding', '').lower()184- if self._decoder is None:185- if content_encoding in self.CONTENT_DECODERS:186- self._decoder = _get_decoder(content_encoding)226+ self._init_decoder()227 if decode_content is None:228 decode_content = self.decode_content229 230 if self._fp is None:40 unmodified lines271 raise ProtocolError('Connection broken: %r' % e, e)272 273 self._fp_bytes_read += len(data)274 235- try:236- if decode_content and self._decoder:237- data = self._decoder.decompress(data)238- except (IOError, zlib.error) as e:239- raise DecodeError(240- "Received response with content-encoding: %s, but "241- "failed to decode it." % content_encoding, e)275+ data = self._decode(data, decode_content, flush_decoder)276 243- if flush_decoder and decode_content and self._decoder:244- buf = self._decoder.decompress(binary_type())245- data += buf + self._decoder.flush()246-277 if cache_content:278 self._body = data279 280 return data17 unmodified lines298 :param decode_content:299 If True, will attempt to decode the body based on the300 'content-encoding' header.301 """302+ if self.chunked:303+ for line in self.read_chunked(amt, decode_content=decode_content):304+ yield line305+ else:272- while not is_fp_closed(self._fp):273- data = self.read(amt=amt, decode_content=decode_content)306+ while not is_fp_closed(self._fp):307+ data = self.read(amt=amt, decode_content=decode_content)308 275- if data:276- yield data309+ if data:310+ yield data311 312 @classmethod313 def from_httplib(ResponseCls, r, **response_kw):314 """69 unmodified lines384 return 0385 else:386 b[:len(temp)] = temp387 return len(temp)388+389+ def _update_chunk_length(self):390+ # First, we'll figure out length of a chunk and then391+ # we'll try to read it from socket.392+ if self.chunk_left is not None:393+ return394+ line = self._fp.fp.readline()395+ line = line.split(b';', 1)[0]396+ try:397+ self.chunk_left = int(line, 16)398+ except ValueError:399+ # Invalid chunked protocol response, abort.400+ self.close()401+ raise httplib.IncompleteRead(line)402+403+ def _handle_chunk(self, amt):404+ returned_chunk = None405+ if amt is None:406+ chunk = self._fp._safe_read(self.chunk_left)407+ returned_chunk = chunk408+ self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.409+ self.chunk_left = None410+ elif amt < self.chunk_left:411+ value = self._fp._safe_read(amt)412+ self.chunk_left = self.chunk_left - amt413+ returned_chunk = value414+ elif amt == self.chunk_left:415+ value = self._fp._safe_read(amt)416+ self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.417+ self.chunk_left = None418+ returned_chunk = value419+ else: # amt > self.chunk_left420+ returned_chunk = self._fp._safe_read(self.chunk_left)421+ self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.422+ self.chunk_left = None423+ return returned_chunk424+425+ def read_chunked(self, amt=None, decode_content=None):426+ """427+ Similar to :meth:`HTTPResponse.read`, but with an additional428+ parameter: ``decode_content``.429+430+ :param decode_content:431+ If True, will attempt to decode the body based on the432+ 'content-encoding' header.433+ """434+ self._init_decoder()435+ # FIXME: Rewrite this method and make it a class with a better structured logic.436+ if not self.chunked:437+ raise ResponseNotChunked("Response is not chunked. "438+ "Header 'transfer-encoding: chunked' is missing.")439+440+ if self._original_response and self._original_response._method.upper() == 'HEAD':441+ # Don't bother reading the body of a HEAD request.442+ # FIXME: Can we do this somehow without accessing private httplib _method?443+ self._original_response.close()444+ return445+446+ while True:447+ self._update_chunk_length()448+ if self.chunk_left == 0:449+ break450+ chunk = self._handle_chunk(amt)451+ yield self._decode(chunk, decode_content=decode_content,452+ flush_decoder=True)453+454+ # Chunk content ends with \r\n: discard it.455+ while True:456+ line = self._fp.fp.readline()457+ if not line:458+ # Some sites may not end with '\r\n'.459+ break460+ if line == b'\r\n':461+ break462+463+ # We read everything; close the "file".464+ if self._original_response:465+ self._original_response.close()466+ self.release_conn()modified:requests/packages/__init__.py+1 added-105 removed
1-"""2-Copyright (c) Donald Stufft, pip, and individual contributors3-4-Permission is hereby granted, free of charge, to any person obtaining5-a copy of this software and associated documentation files (the6-"Software"), to deal in the Software without restriction, including7-without limitation the rights to use, copy, modify, merge, publish,8-distribute, sublicense, and/or sell copies of the Software, and to9-permit persons to whom the Software is furnished to do so, subject to10-the following conditions:11-12-The above copyright notice and this permission notice shall be13-included in all copies or substantial portions of the Software.14-15-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,16-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF17-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND18-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE19-LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION20-OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION21-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.22-"""1 from __future__ import absolute_import2 25-import sys26-27-28-class VendorAlias(object):29-30- def __init__(self, package_names):31- self._package_names = package_names32- self._vendor_name = __name__33- self._vendor_pkg = self._vendor_name + "."34- self._vendor_pkgs = [35- self._vendor_pkg + name for name in self._package_names36- ]37-38- def find_module(self, fullname, path=None):39- if fullname.startswith(self._vendor_pkg):40- return self41-42- def load_module(self, name):43- # Ensure that this only works for the vendored name44- if not name.startswith(self._vendor_pkg):45- raise ImportError(46- "Cannot import %s, must be a subpackage of '%s'." % (47- name, self._vendor_name,48- )49- )50-51- if not (name == self._vendor_name or52- any(name.startswith(pkg) for pkg in self._vendor_pkgs)):53- raise ImportError(54- "Cannot import %s, must be one of %s." % (55- name, self._vendor_pkgs56- )57- )58-59- # Check to see if we already have this item in sys.modules, if we do60- # then simply return that.61- if name in sys.modules:62- return sys.modules[name]63-64- # Check to see if we can import the vendor name65- try:66- # We do this dance here because we want to try and import this67- # module without hitting a recursion error because of a bunch of68- # VendorAlias instances on sys.meta_path69- real_meta_path = sys.meta_path[:]70- try:71- sys.meta_path = [72- m for m in sys.meta_path73- if not isinstance(m, VendorAlias)74- ]75- __import__(name)76- module = sys.modules[name]77- finally:78- # Re-add any additions to sys.meta_path that were made while79- # during the import we just did, otherwise things like80- # requests.packages.urllib3.poolmanager will fail.81- for m in sys.meta_path:82- if m not in real_meta_path:83- real_meta_path.append(m)84-85- # Restore sys.meta_path with any new items.86- sys.meta_path = real_meta_path87- except ImportError:88- # We can't import the vendor name, so we'll try to import the89- # "real" name.90- real_name = name[len(self._vendor_pkg):]91- try:92- __import__(real_name)93- module = sys.modules[real_name]94- except ImportError:95- raise ImportError("No module named '%s'" % (name,))96-97- # If we've gotten here we've found the module we're looking for, either98- # as part of our vendored package, or as the real name, so we'll add99- # it to sys.modules as the vendored name so that we don't have to do100- # the lookup again.101- sys.modules[name] = module102-103- # Finally, return the loaded module104- return module105-106-107-sys.meta_path.insert(0, VendorAlias(["urllib3", "chardet"]))3+from . import urllib3modified:requests/__init__.py+2 added-2 removed
40 unmodified lines41 42 """43 44 __title__ = 'requests'45-__version__ = '2.6.0'46-__build__ = 0x02060045+__version__ = '2.7.0'46+__build__ = 0x02070047 __author__ = 'Kenneth Reitz'48 __license__ = 'Apache 2.0'49 __copyright__ = 'Copyright 2015 Kenneth Reitz'50 27 unmodified linesmodified:requests/api.py+3 added-2 removed
53 unmodified lines54 session.close()55 return response56 57 58-def get(url, **kwargs):58+def get(url, params=None, **kwargs):59 """Sends a GET request.60 61 :param url: URL for the new :class:`Request` object.62+ :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.63 :param \*\*kwargs: Optional arguments that ``request`` takes.64 :return: :class:`Response <Response>` object65 :rtype: requests.Response66 """67 68 kwargs.setdefault('allow_redirects', True)68- return request('get', url, **kwargs)69+ return request('get', url, params=params, **kwargs)70 71 72 def options(url, **kwargs):73 """Sends a OPTIONS request.74 unmodified linesmodified:requests/models.py+4 added
511 unmodified lines512 self.headers['Cookie'] = cookie_header513 514 def prepare_hooks(self, hooks):515 """Prepares the given hooks."""516+ # hooks can be passed as None to the prepare method and to this517+ # method. To prevent iterating over None, simply use an empty list518+ # if hooks is False-y519+ hooks = hooks or []520 for event in hooks:521 self.register_hook(event, hooks[event])522 523 318 unmodified linesmodified:HISTORY.rst+42 added
1 unmodified line2 3 Release History4 ---------------5 6+2.7.0 (2015-05-03)7+++++++++++++++++++8+9+This is the first release that follows our new release process. For more, see10+`our documentation11+<http://docs.python-requests.org/en/latest/community/release-process/>`_.12+13+**Bugfixes**14+15+- Updated urllib3 to 1.10.4, resolving several bugs involving chunked transfer16+ encoding and response framing.17+18+2.6.2 (2015-04-23)19+++++++++++++++++++20+21+**Bugfixes**22+23+- Fix regression where compressed data that was sent as chunked data was not24+ properly decompressed. (#2561)25+26+2.6.1 (2015-04-22)27+++++++++++++++++++28+29+**Bugfixes**30+31+- Remove VendorAlias import machinery introduced in v2.5.2.32+33+- Simplify the PreparedRequest.prepare API: We no longer require the user to34+ pass an empty list to the hooks keyword argument. (c.f. #2552)35+36+- Resolve redirects now receives and forwards all of the original arguments to37+ the adapter. (#2503)38+39+- Handle UnicodeDecodeErrors when trying to deal with a unicode URL that40+ cannot be encoded in ASCII. (#2540)41+42+- Populate the parsed path of the URI field when performing Digest43+ Authentication. (#2426)44+45+- Copy a PreparedRequest's CookieJar more reliably when it is not an instance46+ of RequestsCookieJar. (#2527)47+48 2.6.0 (2015-03-14)49 ++++++++++++++++++50 51 **Bugfixes**980 unmodified linesmodified:test_requests.py-1 removed
1611 unmodified lines1612 p = PreparedRequest()1613 p.prepare(1614 method='GET',1615 url=u('http://www.example.com/üniçø∂é'),1616- hooks=[]1616 )1617 assert_copy(p, p.copy())1618 1619 19 unmodified lines