Skip to content
Myr

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

21 files+475 added−204 removed

modified:docs/community/out-there.rst+1 added
28 unmodified lines
29- `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 lines
42to provide authentication. It also provides a lot of tweaks that handle ways43that specific OAuth providers differ from the standard specifications.4445.. _requests-oauthlib: https://requests-oauthlib.readthedocs.org/en/latest/464748Betamax49-------5051`Betamax`_ records your HTTP interactions so the NSA does not have to.52A VCR imitation designed only for Python-Requests.5354.. _betamax: https://github.com/sigmavirus24/betamax555657
added:docs/community/release-process.rst+54 added
1Release Process and Rules2=========================34.. versionadded:: v2.6.256Starting with the version to be released after ``v2.6.2``, the following rules7will govern and describe how the Requests core team produces a new release.89Major Releases10--------------1112A major release will include breaking changes. When it is versioned, it will13be versioned as ``vX.0.0``. For example, if the previous release was14``v10.2.7`` the next version will be ``v11.0.0``.1516Breaking changes are changes that break backwards compatibility with prior17versions. If the project were to change the ``text`` attribute on a18``Response`` object to a method, that would only happen in a Major release.1920Major releases may also include miscellaneous bug fixes and upgrades to21vendored packages. The core developers of Requests are committed to providing22a good user experience. This means we're also committed to preserving23backwards compatibility as much as possible. Major releases will be infrequent24and will need strong justifications before they are considered.2526Minor Releases27--------------2829A minor release will not include breaking changes but may include30miscellaneous bug fixes and upgrades to vendored packages. If the previous31version of Requests released was ``v10.2.7`` a minor release would be32versioned as ``v10.3.0``.3334Minor releases will be backwards compatible with releases that have the same35major version number. In other words, all versions that would start with36``v10.`` should be compatible with each other.3738Hotfix Releases39---------------4041A hotfix release will only include bug fixes that were missed when the project42released the previous version. If the previous version of Requests released43``v10.2.7`` the hotfix release would be versioned as ``v10.2.8``.4445Hotfixes will **not** include upgrades to vendored dependences after46``v2.6.2``4748Reasoning49---------5051In the 2.5 and 2.6 release series, the Requests core team upgraded vendored52dependencies and caused a great deal of headaches for both users and the core53team. To reduce this pain, we're forming a concrete set of procedures so54expectations will be properly set.
modified:docs/community/updates.rst+3 added-14 removed
1.. _updates:23454Community Updates5=================67If you'd like to stay up to date on the community and development of Requests,
8 unmodified lines
1617Twitter18-------1922I often tweet about new features and releases of Requests.20The author, Kenneth Reitz, often tweets about new features and releases of Requests.2122Follow `@kennethreitz <https://twitter.com/kennethreitz>`_ for updates.232427Mailing List28------------2530There's a low-volume mailing list for Requests. To subscribe to the31mailing list, send an email to32`requests@librelist.org <mailto:requests@librelist.org>`_.26Release and Version History27===========================2834353637Software Updates38================3929.. include:: ../../HISTORY.rst30
added:docs/dev/contributing.rst+145 added
1.. _contributing:23Contributor's Guide4===================56If you're reading this you're probably interested in contributing to7Requests. First, We'd like to say: thank you! Open source projects8live-and-die based on the support they receive from others, and the fact that9you're even considering supporting Requests is very generous of10you.1112This document lays out guidelines and advice for contributing to Requests.13If you're thinking of contributing, start by reading this thoroughly and14getting a feel for how contributing to the project works. If you have any15questions, feel free to reach out to either `Ian Cordasco`_ or `Cory Benfield`_,16the primary maintainers.1718The guide is split into sections based on the type of contribution you're19thinking of making, with a section that covers general guidelines for all20contributors.2122.. _Ian Cordasco: http://www.coglib.com/~icordasc/23.. _Cory Benfield: https://lukasa.co.uk/about242526All Contributions27-----------------2829Be Cordial30~~~~~~~~~~3132**Be cordial or be on your way.**3334Requests has one very important rule governing all forms of contribution,35including reporting bugs or requesting features. This golden rule is36`be cordial or be on your way`_. **All contributions are welcome**, as long as37everyone involved is treated with respect.3839.. _be cordial or be on your way: http://kennethreitz.org/be-cordial-or-be-on-your-way/4041.. _early-feedback:4243Get Early Feedback44~~~~~~~~~~~~~~~~~~4546If you are contributing, do not feel the need to sit on your contribution until47it is perfectly polished and complete. It helps everyone involved for you to48seek feedback as early as you possibly can. Submitting an early, unfinished49version of your contribution for feedback in no way prejudices your chances of50getting that contribution accepted, and can save you from putting a lot of work51into a contribution that is not suitable for the project.5253Contribution Suitability54~~~~~~~~~~~~~~~~~~~~~~~~5556The project maintainer has the last word on whether or not a contribution is57suitable for Requests. All contributions will be considered, but from time58to time contributions will be rejected because they do not suit the project.5960If your contribution is rejected, don't despair! So long as you followed these61guidelines, you'll have a much better chance of getting your next contribution62accepted.636465Code Contributions66------------------6768Steps69~~~~~7071When contributing code, you'll want to follow this checklist:72731. Fork the repository on GitHub.742. 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`.783. Write tests that demonstrate your bug or feature. Ensure that they fail.794. Make your change.805. Run the entire test suite again, confirming that all tests pass *including81 the ones you just added*.826. 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.8586The following sub-sections go into more detail on some of the points above.8788Code Review89~~~~~~~~~~~9091Contributions will not be merged until they've been code reviewed. You should92implement any code review feedback unless you strongly object to it. In the93event that you object to the code review feedback, you should make your case94clearly and calmly. If, after doing so, the feedback is judged to still apply,95you must either apply the feedback or withdraw your contribution.9697New Contributors98~~~~~~~~~~~~~~~~99100If you are new or relatively new to Open Source, welcome! Requests aims to101be a gentle introduction to the world of Open Source. If you're concerned about102how best to contribute, please consider mailing a maintainer (listed above) and103asking for help.104105Please also check the :ref:`early-feedback` section.106107Documentation Contributions108---------------------------109110Documentation improvements are always welcome! The documentation files live in111the ``docs/`` directory of the codebase. They're written in112`reStructuredText`_, and use `Sphinx`_ to generate the full suite of113documentation.114115When contributing documentation, please attempt to follow the style of the116documentation files. This means a soft-limit of 79 characters wide in your text117files and a semi-formal prose style.118119.. _reStructuredText: http://docutils.sourceforge.net/rst.html120.. _Sphinx: http://sphinx-doc.org/index.html121122123.. _bug-reports:124125Bug Reports126-----------127128Bug reports are hugely important! Before you raise one, though, please check129through the `GitHub issues`_, **both open and closed**, to confirm that the bug130hasn't been reported before. Duplicate bug reports are a huge drain on the time131of other contributors, and should be avoided as much as possible.132133.. _GitHub issues: https://github.com/kennethreitz/requests/issues134135136Feature Requests137----------------138139Requests is in a perpeptual feature freeze. The maintainers believe that140requests contains every major feature currently required by the vast majority141of users.142143If you believe there is a feature missing, feel free to raise a feature144request, but please do be aware that the overwhelming likelihood is that your145feature request will not be accepted.
modified:docs/index.rst+3 added-1 removed
113 unmodified lines
114 :maxdepth: 1115116 community/faq117 community/recommended118 community/out-there.rst118 community/out-there119 community/support120 community/vulnerabilities121 community/updates122 community/release-process123124API Documentation125-----------------126
14 unmodified lines
141142.. toctree::143 :maxdepth: 1144145 dev/contributing146 dev/philosophy147 dev/todo148 dev/authors
modified:requests/packages/urllib3/contrib/pyopenssl.py+4 added-19 removed
36 unmodified lines
37Module Variables38----------------3940: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``4142.. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication43.. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)44
37 unmodified lines
82 ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER83 + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,84}8588# 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.101DEFAULT_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"86DEFAULT_SSL_CIPHER_LIST = util.ssl_.DEFAULT_CIPHERS878889orig_util_HAS_SNI = util.HAS_SNI90orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket
190 unmodified lines
281 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 break
2 unmodified lines
modified:requests/packages/urllib3/util/ssl_.py+26 added-12 removed
7 unmodified lines
8HAS_SNI = False9create_default_context = None1011import errno12import ssl12import warnings1314try: # Test for SSL features15 import ssl16 from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv2317 from ssl import HAS_SNI # Has SNI?18except ImportError:19 pass
4 unmodified lines
24except ImportError:25 OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x200000026 OP_NO_COMPRESSION = 0x200002728# 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,28try:29 from ssl import _DEFAULT_CIPHERS30except 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.41DEFAULT_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)4647try:48 from ssl import SSLContext # Modern SSL?49except ImportError:50 import sys5152 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)5556 def __init__(self, protocol_version):57 self.protocol = protocol_version58 # Use default values from a real SSLContext
118 unmodified lines
177178 return candidate179180170def create_urllib3_context(ssl_version=None, cert_reqs=ssl.CERT_REQUIRED,181def 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``.184185 By default, this function does a lot of the same work that
28 unmodified lines
214 :rtype: SSLContext215 """216 context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)217218 # 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_reqs220221 if options is None:222 options = 0223 # SSLv2 is easily broken and is considered harmful and dangerous224 options |= OP_NO_SSLv2
5 unmodified lines
230231 context.options |= options232233 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)235236 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 alternative
42 unmodified lines
modified:requests/packages/urllib3/util/url.py+2 added
13 unmodified lines
14 slots = ()1516 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)2223 @property
191 unmodified lines
modified:requests/packages/urllib3/__init__.py+6 added-3 removed
2 unmodified lines
3"""45__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'6__license__ = 'MIT'7__version__ = '1.10.2'7__version__ = '1.10.4'8910from .connectionpool import (11 HTTPConnectionPool,
42 unmodified lines
54# ... Clean up.55del NullHandler565758# Set security warning to always go off by default.58import warnings59# SecurityWarning's always go off by default.60warnings.simplefilter('always', exceptions.SecurityWarning)60warnings.simplefilter('always', exceptions.SecurityWarning, append=True)61# InsecurePlatformWarning's don't vary between requests, so we keep it default.62warnings.simplefilter('default', exceptions.InsecurePlatformWarning,63 append=True)6465def disable_warnings(category=exceptions.HTTPWarning):66 """67 Helper for quickly disabling all urllib3 warnings.
2 unmodified lines
modified:requests/packages/urllib3/_collections.py+24 added-21 removed
225 unmodified lines
226 # 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])229230 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 lines
303 def items(self):304 return list(self.iteritems())305306 @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()))322323 return cls(headers)
modified:requests/packages/urllib3/connection.py+2 added
258 unmodified lines
259if ssl:260 # Make a copy for testing.261 UnverifiedHTTPSConnection = HTTPSConnection262 HTTPSConnection = VerifiedHTTPSConnection263else:264 HTTPSConnection = DummyConnection
modified:requests/packages/urllib3/connectionpool.py-1 removed
733 unmodified lines
734 log.info("Starting new HTTPS connection (%d): %s"735 % (self.num_connections, self.host))736737 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.")740741 actual_host = self.host
54 unmodified lines
modified:requests/packages/urllib3/exceptions.py+5 added
160 unmodified lines
161162class InsecurePlatformWarning(SecurityWarning):163 "Warned when certain SSL configuration is not available on a platform."164 pass165166167class ResponseNotChunked(ProtocolError, ValueError):168 "Response needs to be chunked in order to read it as chunks."169 pass
modified:requests/packages/urllib3/response.py+136 added-23 removed
1try:2 import http.client as httplib3except ImportError:4 import httplib5import zlib6import io7from socket import timeout as SocketTimeout89from ._collections import HTTPHeaderDict6from .exceptions import ProtocolError, DecodeError, ReadTimeoutError10from .exceptions import (11 ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked12)13from .packages.six import string_types as basestring, binary_type, PY314from .connection import HTTPException, BaseSSLError15from .util.response import is_fp_closed16
105 unmodified lines
122123 if hasattr(body, 'read'):124 self._fp = body125126 # 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 = True134135 # 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)138139 def get_redirect_location(self):140 """
31 unmodified lines
172 are encoded on the wire (e.g, compressed).173 """174 return self._fp_bytes_read175176 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)185186 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)198199 if flush_decoder and decode_content and self._decoder:200 buf = self._decoder.decompress(binary_type())201 data += buf + self._decoder.flush()202203 return data204205 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 lines
222 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_content229230 if self._fp is None:
40 unmodified lines
271 raise ProtocolError('Connection broken: %r' % e, e)272273 self._fp_bytes_read += len(data)274235 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)276243 if flush_decoder and decode_content and self._decoder:244 buf = self._decoder.decompress(binary_type())245 data += buf + self._decoder.flush()246277 if cache_content:278 self._body = data279280 return data
17 unmodified lines
298 :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)308275 if data:276 yield data309 if data:310 yield data311312 @classmethod313 def from_httplib(ResponseCls, r, **response_kw):314 """
69 unmodified lines
384 return 0385 else:386 b[:len(temp)] = temp387 return len(temp)388389 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)402403 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_chunk424425 def read_chunked(self, amt=None, decode_content=None):426 """427 Similar to :meth:`HTTPResponse.read`, but with an additional428 parameter: ``decode_content``.429430 :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.")439440 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 return445446 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)453454 # 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 break462463 # 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"""2Copyright (c) Donald Stufft, pip, and individual contributors34Permission is hereby granted, free of charge, to any person obtaining5a copy of this software and associated documentation files (the6"Software"), to deal in the Software without restriction, including7without limitation the rights to use, copy, modify, merge, publish,8distribute, sublicense, and/or sell copies of the Software, and to9permit persons to whom the Software is furnished to do so, subject to10the following conditions:1112The above copyright notice and this permission notice shall be13included in all copies or substantial portions of the Software.1415THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,16EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF17MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND18NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE19LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION20OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION21WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.22"""1from __future__ import absolute_import225import sys262728class VendorAlias(object):2930 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 ]3738 def find_module(self, fullname, path=None):39 if fullname.startswith(self._vendor_pkg):40 return self4142 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 )5051 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 )5859 # 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]6364 # 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)8485 # 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,))9697 # 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] = module102103 # Finally, return the loaded module104 return module105106107sys.meta_path.insert(0, VendorAlias(["urllib3", "chardet"]))3from . import urllib3
modified:requests/__init__.py+2 added-2 removed
40 unmodified lines
4142"""4344__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 lines
modified:requests/api.py+3 added-2 removed
53 unmodified lines
54 session.close()55 return response565758def get(url, **kwargs):58def get(url, params=None, **kwargs):59 """Sends a GET request.6061 :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 """6768 kwargs.setdefault('allow_redirects', True)68 return request('get', url, **kwargs)69 return request('get', url, params=params, **kwargs)707172def options(url, **kwargs):73 """Sends a OPTIONS request.
74 unmodified lines
modified:requests/models.py+4 added
511 unmodified lines
512 self.headers['Cookie'] = cookie_header513514 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])522523
318 unmodified lines
modified:HISTORY.rst+42 added
1 unmodified line
23Release History4---------------562.7.0 (2015-05-03)7++++++++++++++++++89This 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/>`_.1213**Bugfixes**1415- Updated urllib3 to 1.10.4, resolving several bugs involving chunked transfer16 encoding and response framing.17182.6.2 (2015-04-23)19++++++++++++++++++2021**Bugfixes**2223- Fix regression where compressed data that was sent as chunked data was not24 properly decompressed. (#2561)25262.6.1 (2015-04-22)27++++++++++++++++++2829**Bugfixes**3031- Remove VendorAlias import machinery introduced in v2.5.2.3233- Simplify the PreparedRequest.prepare API: We no longer require the user to34 pass an empty list to the hooks keyword argument. (c.f. #2552)3536- Resolve redirects now receives and forwards all of the original arguments to37 the adapter. (#2503)3839- Handle UnicodeDecodeErrors when trying to deal with a unicode URL that40 cannot be encoded in ASCII. (#2540)4142- Populate the parsed path of the URI field when performing Digest43 Authentication. (#2426)4445- Copy a PreparedRequest's CookieJar more reliably when it is not an instance46 of RequestsCookieJar. (#2527)47482.6.0 (2015-03-14)49++++++++++++++++++5051**Bugfixes**
980 unmodified lines
modified:test_requests.py-1 removed
1611 unmodified lines
1612 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())16181619
19 unmodified lines