Skip to content
Myr

Merge branch 'master' of https://github.com/kennethreitz/requests

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by ContinuousFunction · committed by ContinuousFunction · parents 3246b1f, d7c0249 · Browse files · 28 files+504 added−157 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

28 files+504 added−157 removed

  • other:+504 added−157 removed

28 files+504 added−157 removed

modified:docs/user/advanced.rst+14 added-1 removed
3 unmodified lines
4==============56This document covers some of Requests more advanced features.78.. _session-objects:910Session Objects11---------------12
37 unmodified lines
5051All values that are contained within a session are directly available to you.52See the :ref:`Session API Docs <sessionapi>` to learn more.5354.. _request-and-response-objects:5556Request and Response Objects57----------------------------5859Whenever a call is made to ``requests.get()`` and friends you are doing two
24 unmodified lines
84 >>> r.request.headers85 {'Accept-Encoding': 'identity, deflate, compress, gzip',86 'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'}8788.. _prepared-requests:8990Prepared Requests91-----------------9293Whenever you receive a :class:`Response <requests.Response>` object
99 unmodified lines
193194 >>> requests.get('https://kennethreitz.com', cert='/wrong_path/server.pem')195 SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib196197.. _body-content-workflow:198199Body Content Workflow200---------------------201
31 unmodified lines
233 # Do things with the response here.234235.. _`documented here`: http://docs.python.org/2/library/contextlib.html#contextlib.closing236237.. _keep-alive:238239Keep-Alive240----------241
4 unmodified lines
246Note that connections are only released back to the pool for reuse once all body247data has been read; be sure to either set ``stream`` to ``False`` or read the248``content`` property of the ``Response`` object.249250.. _streaming-uploads:251252Streaming Uploads253-----------------254
3 unmodified lines
258259 with open('massive-body', 'rb') as f:260 requests.post('http://some.url/streamed', data=f)261262.. _chunk-encoding:263264Chunk-Encoded Requests265----------------------266
8 unmodified lines
275276 requests.post('http://some.url/chunked', data=gen())277278279.. _multipart:280281POST Multiple Multipart-Encoded Files282-------------------------------------283
15 unmodified lines
299 'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a',300 ...301 }302303.. _event-hooks:304305Event Hooks306-----------307
31 unmodified lines
339 >>> requests.get('http://httpbin.org', hooks=dict(response=print_url))340 http://httpbin.org341 <Response [200]>342343.. _custom-auth:344345Custom Authentication346---------------------347
35 unmodified lines
383------------------384385With :class:`requests.Response.iter_lines()` you can easily386iterate over streaming APIs such as the `Twitter Streaming375API <https://dev.twitter.com/docs/streaming-api>`_. Simply387API <https://dev.twitter.com/streaming/overview>`_. Simply388set ``stream`` to ``True`` and iterate over the response with389:class:`~requests.Response.iter_lines()`::390391 import json
6 unmodified lines
398 # filter out keep-alive new lines399 if line:400 print(json.loads(line))401402.. _proxies:403404Proxies405-------406
392 unmodified lines
modified:requests/packages/chardet/__init__.py+1 added-1 removed
13 unmodified lines
14# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA15# 02110-1301 USA16######################### END LICENSE BLOCK #########################1718__version__ = "2.2.1"18__version__ = "2.3.0"19from sys import version_info202122def detect(aBuf):
10 unmodified lines
modified:requests/packages/chardet/chardetect.py+49 added-15 removed
10 unmodified lines
1112If no paths are provided, it takes its input from stdin.1314"""1516from __future__ import absolute_import, print_function, unicode_literals1718import argparse19import sys20from io import open16from sys import argv, stdin2122from chardet import __version__23from chardet.universaldetector import UniversalDetector242521def description_of(file, name='stdin'):22 """Return a string describing the probable encoding of a file."""26def description_of(lines, name='stdin'):27 """28 Return a string describing the probable encoding of a file or29 list of strings.3031 :param lines: The lines to get the encoding of.32 :type lines: Iterable of bytes33 :param name: Name of file or collection of lines34 :type name: str35 """36 u = UniversalDetector()24 for line in file:37 for line in lines:38 u.feed(line)39 u.close()40 result = u.result41 if result['encoding']:29 return '%s: %s with confidence %s' % (name,30 result['encoding'],31 result['confidence'])42 return '{0}: {1} with confidence {2}'.format(name, result['encoding'],43 result['confidence'])44 else:33 return '%s: no result' % name45 return '{0}: no result'.format(name)464736def main():37 if len(argv) <= 1:38 print(description_of(stdin))39 else:40 for path in argv[1:]:41 with open(path, 'rb') as f:42 print(description_of(f, path))48def main(argv=None):49 '''50 Handles command line arguments and gets things started.5152 :param argv: List of arguments, as if specified on the command-line.53 If None, ``sys.argv[1:]`` is used instead.54 :type argv: list of str55 '''56 # Get command line arguments57 parser = argparse.ArgumentParser(58 description="Takes one or more file paths and reports their detected \59 encodings",60 formatter_class=argparse.ArgumentDefaultsHelpFormatter,61 conflict_handler='resolve')62 parser.add_argument('input',63 help='File whose encoding we would like to determine.',64 type=argparse.FileType('rb'), nargs='*',65 default=[sys.stdin])66 parser.add_argument('--version', action='version',67 version='%(prog)s {0}'.format(__version__))68 args = parser.parse_args(argv)6970 for f in args.input:71 if f.isatty():72 print("You are running chardetect interactively. Press " +73 "CTRL-D twice at the start of a blank line to signal the " +74 "end of your input. If you want help, run chardetect " +75 "--help\n", file=sys.stderr)76 print(description_of(f, f.name))777879if __name__ == '__main__':80 main()
modified:requests/packages/chardet/jpcntx.py+8 added
175 unmodified lines
176 def get_order(self, aBuf):177 return -1, 1178179class SJISContextAnalysis(JapaneseContextAnalysis):180 def __init__(self):181 self.charset_name = "SHIFT_JIS"182183 def get_charset_name(self):184 return self.charset_name185186 def get_order(self, aBuf):187 if not aBuf:188 return -1, 1189 # find out current char's byte length190 first_char = wrap_ord(aBuf[0])191 if ((0x81 <= first_char <= 0x9F) or (0xE0 <= first_char <= 0xFC)):192 charLen = 2193 if (first_char == 0x87) or (0xFA <= first_char <= 0xFC):194 self.charset_name = "CP932"195 else:196 charLen = 1197198 # return its order if it is hiragana
29 unmodified lines
modified:requests/packages/chardet/latin1prober.py+3 added-3 removed
127 unmodified lines
128 total = sum(self._mFreqCounter)129 if total < 0.01:130 confidence = 0.0131 else:132 confidence = ((self._mFreqCounter[3] / total)133 - (self._mFreqCounter[1] * 20.0 / total))132 confidence = ((self._mFreqCounter[3] - self._mFreqCounter[1] * 20.0)133 / total)134 if confidence < 0.0:135 confidence = 0.0136 # lower the confidence of latin1 so that other more accurate137 # detector can take priority.138 confidence = confidence * 0.5138 confidence = confidence * 0.73139 return confidence
modified:requests/packages/chardet/mbcssm.py+3 added-6 removed
351 unmodified lines
352 2,2,2,2,2,2,2,2, # 60 - 67353 2,2,2,2,2,2,2,2, # 68 - 6f354 2,2,2,2,2,2,2,2, # 70 - 77355 2,2,2,2,2,2,2,1, # 78 - 7f356 3,3,3,3,3,3,3,3, # 80 - 87356 3,3,3,3,3,2,2,3, # 80 - 87357 3,3,3,3,3,3,3,3, # 88 - 8f358 3,3,3,3,3,3,3,3, # 90 - 97359 3,3,3,3,3,3,3,3, # 98 - 9f360 #0xa0 is illegal in sjis encoding, but some pages does
7 unmodified lines
368 2,2,2,2,2,2,2,2, # d0 - d7369 2,2,2,2,2,2,2,2, # d8 - df370 3,3,3,3,3,3,3,3, # e0 - e7371 3,3,3,3,3,4,4,4, # e8 - ef372 4,4,4,4,4,4,4,4, # f0 - f7373 4,4,4,4,4,0,0,0 # f8 - ff374)372 3,3,3,3,3,3,3,3, # f0 - f7373 3,3,3,3,3,0,0,0) # f8 - ff374375376SJIS_st = (377 eError,eStart,eStart, 3,eError,eError,eError,eError,#00-07
191 unmodified lines
569 'classFactor': 16,570 'stateTable': UTF8_st,571 'charLenTable': UTF8CharLenTable,572 'name': 'UTF-8'}574575# flake8: noqa
modified:requests/packages/chardet/sjisprober.py+1 added-1 removed
45 unmodified lines
46 MultiByteCharSetProber.reset(self)47 self._mContextAnalyzer.reset()4849 def get_charset_name(self):50 return "SHIFT_JIS"50 return self._mContextAnalyzer.get_charset_name()5152 def feed(self, aBuf):53 aLen = len(aBuf)54 for i in range(0, aLen):
37 unmodified lines
modified:requests/packages/chardet/universaldetector.py+2 added-2 removed
69 unmodified lines
70 return7172 if not self._mGotData:73 # If the data starts with BOM, we know it is UTF74 if aBuf[:3] == codecs.BOM:74 if aBuf[:3] == codecs.BOM_UTF8:75 # EF BB BF UTF-8 with BOM76 self.result = {'encoding': "UTF-8", 'confidence': 1.0}76 self.result = {'encoding': "UTF-8-SIG", 'confidence': 1.0}77 elif aBuf[:4] == codecs.BOM_UTF32_LE:78 # FF FE 00 00 UTF-32, little-endian BOM79 self.result = {'encoding': "UTF-32LE", 'confidence': 1.0}80 elif aBuf[:4] == codecs.BOM_UTF32_BE:
90 unmodified lines
modified:requests/packages/urllib3/contrib/pyopenssl.py+22 added-3 removed
27 unmodified lines
28Now you can use :mod:`urllib3` as you normally would, and it will support SNI29when the required modules are installed.3031Activating this module also has the positive side effect of disabling SSL/TLS32encryption in Python 2 (see `CRIME attack`_).32compression in Python 2 (see `CRIME attack`_).3334If you want to configure the default list of supported cipher suites, you can35set the ``urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST`` variable.36
32 unmodified lines
6970# Map from urllib3 to PyOpenSSL compatible parameter-values.71_openssl_versions = {72 ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD,73 ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD,73 ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,74}7576try:77 _openssl_versions.update({ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD})78except AttributeError:79 pass8081_openssl_verify = {82 ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,83 ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,84 ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER
118 unmodified lines
203204 def settimeout(self, timeout):205 return self.socket.settimeout(timeout)206207 def _send_until_done(self, data):208 while True:209 try:210 return self.connection.send(data)211 except OpenSSL.SSL.WantWriteError:212 _, wlist, _ = select.select([], [self.socket], [],213 self.socket.gettimeout())214 if not wlist:215 raise timeout()216 continue217218 def sendall(self, data):203 return self.connection.sendall(data)219 while len(data):220 sent = self._send_until_done(data)221 data = data[sent:]222223 def close(self):224 if self._makefile_refs < 1:225 return self.connection.shutdown()
39 unmodified lines
265 ca_certs=None, server_hostname=None,266 ssl_version=None):267 ctx = OpenSSL.SSL.Context(_openssl_versions[ssl_version])268 if certfile:269 keyfile = keyfile or certfile # Match behaviour of the normal python ssl library270 ctx.use_certificate_file(certfile)271 if keyfile:272 ctx.use_privatekey_file(keyfile)273 if cert_reqs != ssl.CERT_NONE:
30 unmodified lines
modified:requests/packages/urllib3/util/retry.py+15 added-9 removed
1import time2import logging34from ..exceptions import (5 ProtocolError,5 ConnectTimeoutError,7 ReadTimeoutError,6 MaxRetryError,7 ProtocolError,8 ReadTimeoutError,9 ResponseError,10)11from ..packages import six1213
22 unmodified lines
3637 Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless38 retries are disabled, in which case the causing exception will be raised.393940 :param int total:41 Total number of retries to allow. Takes precedence over other counts.4243 Set to ``None`` to remove this constraint and fall back on other
139 unmodified lines
183 """184 return isinstance(err, ConnectTimeoutError)185186 def _is_read_error(self, err):187 """ Errors that occur after the request has been started, so we can't188 assume that the server did not process any of it.187 """ Errors that occur after the request has been started, so we should188 assume that the server began processing it.189 """190 return isinstance(err, (ReadTimeoutError, ProtocolError))191192 def is_forced_retry(self, method, status_code):
4 unmodified lines
197198 return self.status_forcelist and status_code in self.status_forcelist199200 def is_exhausted(self):201 """ Are we out of retries?202 """201 """ Are we out of retries? """202 retry_counts = (self.total, self.connect, self.read, self.redirect)203 retry_counts = list(filter(None, retry_counts))204 if not retry_counts:205 return False
22 unmodified lines
228 _observed_errors = self._observed_errors229 connect = self.connect230 read = self.read231 redirect = self.redirect232 cause = 'unknown'233234 if error and self._is_connection_error(error):235 # Connect retry?236 if connect is False:
13 unmodified lines
250 elif response and response.get_redirect_location():251 # Redirect retry?252 if redirect is not None:253 redirect -= 1254 cause = 'too many redirects'255256 else:256 # FIXME: Nothing changed, scenario doesn't make sense.257 # Incrementing because of a server error like a 500 in258 # status_forcelist and a the given method is in the whitelist259 _observed_errors += 1260 cause = ResponseError.GENERIC_ERROR261 if response and response.status:262 cause = ResponseError.SPECIFIC_ERROR.format(263 status_code=response.status)264265 new_retry = self.new(266 total=total,267 connect=connect, read=read, redirect=redirect,268 _observed_errors=_observed_errors)269270 if new_retry.is_exhausted():265 raise MaxRetryError(_pool, url, error)271 raise MaxRetryError(_pool, url, error or ResponseError(cause))272273 log.debug("Incremented Retry for (url='%s'): %r" % (url, new_retry))274275 return new_retry
10 unmodified lines
modified:requests/packages/urllib3/util/ssl_.py+162 added-40 removed
2 unmodified lines
34from ..exceptions import SSLError567try: # Test for SSL features8 SSLContext = None9 HAS_SNI = False7SSLContext = None8HAS_SNI = False9create_default_context = None1011 import ssl11import errno12import ssl1314try: # Test for SSL features15 from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv2313 from ssl import SSLContext # Modern SSL?16 from ssl import HAS_SNI # Has SNI?17except ImportError:18 pass192021try:22 from ssl import OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION23except ImportError:24 OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x200000025 OP_NO_COMPRESSION = 0x200002627try:28 from ssl import _DEFAULT_CIPHERS29except ImportError:30 _DEFAULT_CIPHERS = (31 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'32 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:ECDH+RC4:'33 'DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5'34 )3536try:37 from ssl import SSLContext # Modern SSL?38except ImportError:39 import sys4041 class SSLContext(object): # Platform-specific: Python 2 & 3.142 supports_set_ciphers = sys.version_info >= (2, 7)4344 def __init__(self, protocol_version):45 self.protocol = protocol_version46 # Use default values from a real SSLContext47 self.check_hostname = False48 self.verify_mode = ssl.CERT_NONE49 self.ca_certs = None50 self.options = 051 self.certfile = None52 self.keyfile = None53 self.ciphers = None5455 def load_cert_chain(self, certfile, keyfile):56 self.certfile = certfile57 self.keyfile = keyfile5859 def load_verify_locations(self, location):60 self.ca_certs = location6162 def set_ciphers(self, cipher_suite):63 if not self.supports_set_ciphers:64 raise TypeError(65 'Your version of Python does not support setting '66 'a custom cipher suite. Please upgrade to Python '67 '2.7, 3.2, or later if you need this functionality.'68 )69 self.ciphers = cipher_suite7071 def wrap_socket(self, socket, server_hostname=None):72 kwargs = {73 'keyfile': self.keyfile,74 'certfile': self.certfile,75 'ca_certs': self.ca_certs,76 'cert_reqs': self.verify_mode,77 'ssl_version': self.protocol,78 }79 if self.supports_set_ciphers: # Platform-specific: Python 2.7+80 return wrap_socket(socket, ciphers=self.ciphers, **kwargs)81 else: # Platform-specific: Python 2.682 return wrap_socket(socket, **kwargs)838485def assert_fingerprint(cert, fingerprint):86 """87 Checks if given fingerprint matches the supplied certificate.88
67 unmodified lines
156157 return candidate15815994if SSLContext is not None: # Python 3.2+95 def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,96 ca_certs=None, server_hostname=None,97 ssl_version=None):98 """99 All arguments except `server_hostname` have the same meaning as for100 :func:`ssl.wrap_socket`160def create_urllib3_context(ssl_version=None, cert_reqs=ssl.CERT_REQUIRED,161 options=None, ciphers=None):162 """All arguments have the same meaning as ``ssl_wrap_socket``.163102 :param server_hostname:103 Hostname of the expected certificate104 """105 context = SSLContext(ssl_version)106 context.verify_mode = cert_reqs164 By default, this function does a lot of the same work that165 ``ssl.create_default_context`` does on Python 3.4+. It:166108 # Disable TLS compression to migitate CRIME attack (issue #309)109 OP_NO_COMPRESSION = 0x20000110 context.options |= OP_NO_COMPRESSION167 - Disables SSLv2, SSLv3, and compression168 - Sets a restricted set of server ciphers169112 if ca_certs:113 try:114 context.load_verify_locations(ca_certs)115 # Py32 raises IOError116 # Py33 raises FileNotFoundError117 except Exception as e: # Reraise as SSLError118 raise SSLError(e)119 if certfile:120 # FIXME: This block needs a test.121 context.load_cert_chain(certfile, keyfile)122 if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI123 return context.wrap_socket(sock, server_hostname=server_hostname)124 return context.wrap_socket(sock)170 If you wish to enable SSLv3, you can do::171126else: # Python 3.1 and earlier127 def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,128 ca_certs=None, server_hostname=None,129 ssl_version=None):130 return wrap_socket(sock, keyfile=keyfile, certfile=certfile,131 ca_certs=ca_certs, cert_reqs=cert_reqs,132 ssl_version=ssl_version)172 from urllib3.util import ssl_173 context = ssl_.create_urllib3_context()174 context.options &= ~ssl_.OP_NO_SSLv3175176 You can do the same to enable compression (substituting ``COMPRESSION``177 for ``SSLv3`` in the last line above).178179 :param ssl_version:180 The desired protocol version to use. This will default to181 PROTOCOL_SSLv23 which will negotiate the highest protocol that both182 the server and your installation of OpenSSL support.183 :param cert_reqs:184 Whether to require the certificate verification. This defaults to185 ``ssl.CERT_REQUIRED``.186 :param options:187 Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,188 ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``.189 :param ciphers:190 Which cipher suites to allow the server to select.191 :returns:192 Constructed SSLContext object with specified options193 :rtype: SSLContext194 """195 context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)196197 if options is None:198 options = 0199 # SSLv2 is easily broken and is considered harmful and dangerous200 options |= OP_NO_SSLv2201 # SSLv3 has several problems and is now dangerous202 options |= OP_NO_SSLv3203 # Disable compression to prevent CRIME attacks for OpenSSL 1.0+204 # (issue #309)205 options |= OP_NO_COMPRESSION206207 context.options |= options208209 if getattr(context, 'supports_set_ciphers', True): # Platform-specific: Python 2.6210 context.set_ciphers(ciphers or _DEFAULT_CIPHERS)211212 context.verify_mode = cert_reqs213 if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2214 context.check_hostname = (context.verify_mode == ssl.CERT_REQUIRED)215 return context216217218def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,219 ca_certs=None, server_hostname=None,220 ssl_version=None, ciphers=None, ssl_context=None):221 """222 All arguments except for server_hostname and ssl_context have the same223 meaning as they do when using :func:`ssl.wrap_socket`.224225 :param server_hostname:226 When SNI is supported, the expected hostname of the certificate227 :param ssl_context:228 A pre-made :class:`SSLContext` object. If none is provided, one will229 be created using :func:`create_urllib3_context`.230 :param ciphers:231 A string of ciphers we wish the client to support. This is not232 supported on Python 2.6 as the ssl module does not support it.233 """234 context = ssl_context235 if context is None:236 context = create_urllib3_context(ssl_version, cert_reqs,237 ciphers=ciphers)238239 if ca_certs:240 try:241 context.load_verify_locations(ca_certs)242 except IOError as e: # Platform-specific: Python 2.6, 2.7, 3.2243 raise SSLError(e)244 # Py33 raises FileNotFoundError which subclasses OSError245 # These are not equivalent unless we check the errno attribute246 except OSError as e: # Platform-specific: Python 3.3 and beyond247 if e.errno == errno.ENOENT:248 raise SSLError(e)249 raise250 if certfile:251 context.load_cert_chain(certfile, keyfile)252 if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI253 return context.wrap_socket(sock, server_hostname=server_hostname)254 return context.wrap_socket(sock)
modified:requests/packages/urllib3/util/url.py+43 added-2 removed
38 unmodified lines
39 if self.port:40 return '%s:%d' % (self.host, self.port)41 return self.host4243 @property44 def url(self):45 """46 Convert self into a url4748 This function should more or less round-trip with :func:`.parse_url`. The49 returned url may not be exactly the same as the url inputted to50 :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls51 with a blank port will have : removed).5253 Example: ::5455 >>> U = parse_url('http://google.com/mail/')56 >>> U.url57 'http://google.com/mail/'58 >>> Url('http', 'username:password', 'host.com', 80,59 ... '/path', 'query', 'fragment').url60 'http://username:password@host.com:80/path?query#fragment'61 """62 scheme, auth, host, port, path, query, fragment = self63 url = ''6465 # We use "is not None" we want things to happen with empty strings (or 0 port)66 if scheme is not None:67 url += scheme + '://'68 if auth is not None:69 url += auth + '@'70 if host is not None:71 url += host72 if port is not None:73 url += ':' + str(port)74 if path is not None:75 url += path76 if query is not None:77 url += '?' + query78 if fragment is not None:79 url += '#' + fragment8081 return url8283 def __str__(self):84 return self.url8586def split_first(s, delims):87 """88 Given a string and an iterable of delimiters, split on the first found89 delimiter. Return two split parts and the matched delimiter.
35 unmodified lines
125126 Example::127128 >>> parse_url('http://google.com/mail/')87 Url(scheme='http', host='google.com', port=None, path='/', ...)129 Url(scheme='http', host='google.com', port=None, path='/mail/', ...)130 >>> parse_url('google.com:80')131 Url(scheme=None, host='google.com', port=80, path=None, ...)132 >>> parse_url('/foo?bar')133 Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)
69 unmodified lines
203 path, query = path.split('?', 1)204205 return Url(scheme, auth, host, port, path, query, fragment)206165207def get_host(url):208 """209 Deprecated. Use :func:`.parse_url` instead.210 """
2 unmodified lines
modified:requests/packages/urllib3/__init__.py+1 added-1 removed
55 unmodified lines
565758# Set security warning to only go off once by default.59import warnings60warnings.simplefilter('module', exceptions.SecurityWarning)60warnings.simplefilter('always', exceptions.SecurityWarning)6162def disable_warnings(category=exceptions.HTTPWarning):63 """64 Helper for quickly disabling all urllib3 warnings.
2 unmodified lines
modified:requests/packages/urllib3/_collections.py+3 added-4 removed
12 unmodified lines
13try: # Python 2.7+14 from collections import OrderedDict15except ImportError:16 from .packages.ordered_dict import OrderedDict17from .packages.six import itervalues17from .packages.six import iterkeys, itervalues181920__all__ = ['RecentlyUsedContainer', 'HTTPHeaderDict']21
62 unmodified lines
8485 def clear(self):86 with self.lock:87 # Copy pointers to all values, then wipe the mapping88 # under Python 2, this copies the list of values twice :-|89 values = list(self._container.values())88 values = list(itervalues(self._container))89 self._container.clear()9091 if self.dispose_func:92 for value in values:93 self.dispose_func(value)9495 def keys(self):96 with self.lock:98 return self._container.keys()97 return list(iterkeys(self._container))9899100class HTTPHeaderDict(MutableMapping):101 """
97 unmodified lines
modified:requests/packages/urllib3/connection.py+20 added-4 removed
1 unmodified line
2import sys3import socket4from socket import timeout as SocketTimeout5import warnings6from .packages import six78try: # Python 39 from http.client import HTTPConnection as _HTTPConnection, HTTPException10except ImportError:
15 unmodified lines
26 class BaseSSLError(BaseException):27 pass282930try: # Python 3:31 # Not a no-op, we're adding this to the namespace so it can be imported.32 ConnectionError = ConnectionError33except NameError: # Python 2:34 class ConnectionError(Exception):35 pass363738from .exceptions import (39 ConnectTimeoutError,40 SystemTimeWarning,41 SecurityWarning,42)43from .packages.ssl_match_hostname import match_hostname34from .packages import six4445from .util.ssl_ import (46 resolve_cert_reqs,47 resolve_ssl_version,48 ssl_wrap_socket,49 assert_fingerprint,50)515253from .util import connection544555port_by_scheme = {56 'http': 80,57 'https': 443,58}
182 unmodified lines
241 assert_fingerprint(self.sock.getpeercert(binary_form=True),242 self.assert_fingerprint)243 elif resolved_cert_reqs != ssl.CERT_NONE \244 and self.assert_hostname is not False:236 match_hostname(self.sock.getpeercert(),237 self.assert_hostname or hostname)245 cert = self.sock.getpeercert()246 if not cert.get('subjectAltName', ()):247 warnings.warn((248 'Certificate has no `subjectAltName`, falling back to check for a `commonName` for now. '249 'This feature is being removed by major browsers and deprecated by RFC 2818. '250 '(See https://github.com/shazow/urllib3/issues/497 for details.)'),251 SecurityWarning252 )253 match_hostname(cert, self.assert_hostname or hostname)254255 self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED256 or self.assert_fingerprint is not None)257
5 unmodified lines
modified:requests/packages/urllib3/connectionpool.py+34 added-30 removed
30 unmodified lines
31from .connection import (32 port_by_scheme,33 DummyConnection,34 HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,35 HTTPException, BaseSSLError,35 HTTPException, BaseSSLError, ConnectionError36)37from .request import RequestMethods38from .response import HTTPResponse39
237 unmodified lines
277 # User passed us an int/float. This is for backwards compatibility,278 # can be removed later279 return Timeout.from_float(timeout)280281 def _raise_timeout(self, err, url, timeout_value):282 """Is the error actually a timeout? Will raise a ReadTimeout or pass"""283284 if isinstance(err, SocketTimeout):285 raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)286287 # See the above comment about EAGAIN in Python 3. In Python 2 we have288 # to specifically catch it and throw the timeout error289 if hasattr(err, 'errno') and err.errno in _blocking_errnos:290 raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)291292 # Catch possible read timeouts thrown as SSL errors. If not the293 # case, rethrow the original. We need to do this because of:294 # http://bugs.python.org/issue10272295 if 'timed out' in str(err) or 'did not complete (read)' in str(err): # Python 2.6296 raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)297298 def _make_request(self, conn, method, url, timeout=_Default,299 **httplib_request_kw):300 """301 Perform a request on a given urllib connection object taken from our
15 unmodified lines
317 timeout_obj.start_connect()318 conn.timeout = timeout_obj.connect_timeout319320 # Trigger any extra validation we need to do.321 try:304 self._validate_conn(conn)322 self._validate_conn(conn)323 except (SocketTimeout, BaseSSLError) as e:324 # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.325 self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)326 raise327328 # conn.request() calls httplib.*.request, not the method in329 # urllib3.request. It also calls makefile (recv) on the socket.330 conn.request(method, url, **httplib_request_kw)
21 unmodified lines
352 try: # Python 2.7+, use buffering of HTTP responses353 httplib_response = conn.getresponse(buffering=True)354 except TypeError: # Python 2.6 and older355 httplib_response = conn.getresponse()334 except SocketTimeout:335 raise ReadTimeoutError(336 self, url, "Read timed out. (read timeout=%s)" % read_timeout)337338 except BaseSSLError as e:339 # Catch possible read timeouts thrown as SSL errors. If not the340 # case, rethrow the original. We need to do this because of:341 # http://bugs.python.org/issue10272342 if 'timed out' in str(e) or \343 'did not complete (read)' in str(e): # Python 2.6344 raise ReadTimeoutError(345 self, url, "Read timed out. (read timeout=%s)" % read_timeout)346356 except (SocketTimeout, BaseSSLError, SocketError) as e:357 self._raise_timeout(err=e, url=url, timeout_value=read_timeout)358 raise359349 except SocketError as e: # Platform-specific: Python 2350 # See the above comment about EAGAIN in Python 3. In Python 2 we351 # have to specifically catch it and throw the timeout error352 if e.errno in _blocking_errnos:353 raise ReadTimeoutError(354 self, url, "Read timed out. (read timeout=%s)" % read_timeout)355356 raise357360 # AppEngine doesn't have a version attr.361 http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')362 log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,363 httplib_response.status,
174 unmodified lines
538 # Timed out by queue.539 raise EmptyPoolError(self, "No pool connections are available.")540541 except (BaseSSLError, CertificateError) as e:540 # Release connection unconditionally because there is no way to541 # close it externally in case of exception.542 release_conn = True542 # Close the connection. If a connection is reused on which there543 # was a Certificate error, the next request will certainly raise544 # another Certificate error.545 if conn:546 conn.close()547 conn = None548 raise SSLError(e)549545 except (TimeoutError, HTTPException, SocketError) as e:550 except (TimeoutError, HTTPException, SocketError, ConnectionError) as e:551 if conn:552 # Discard the connection for these exceptions. It will be553 # be replaced during the next _get_conn() call.554 conn.close()
174 unmodified lines
729 if not conn.is_verified:730 warnings.warn((731 'Unverified HTTPS request is being made. '732 'Adding certificate verification is strongly advised. See: '728 'https://urllib3.readthedocs.org/en/latest/security.html '729 '(This warning will only appear once by default.)'),733 'https://urllib3.readthedocs.org/en/latest/security.html'),734 InsecureRequestWarning)735736737def connection_from_url(url, **kw):
24 unmodified lines
modified:requests/packages/urllib3/exceptions.py+8 added-5 removed
70 unmodified lines
7172 def __init__(self, pool, url, reason=None):73 self.reason = reason7475 message = "Max retries exceeded with url: %s" % url76 if reason:77 message += " (Caused by %r)" % reason78 else:79 message += " (Caused by redirect)"75 message = "Max retries exceeded with url: %s (Caused by %r)" % (76 url, reason)7778 RequestError.__init__(self, pool, url, message)7980
56 unmodified lines
137138 self.location = location139140141class ResponseError(HTTPError):142 "Used as a container for an error reason supplied in a MaxRetryError."143 GENERIC_ERROR = 'too many error responses'144 SPECIFIC_ERROR = 'too many {status_code} error responses'145146147class SecurityWarning(HTTPWarning):148 "Warned when perfoming security reducing actions"149 pass150
9 unmodified lines
modified:requests/packages/urllib3/request.py+17 added-11 removed
116 unmodified lines
117 be overwritten because it depends on the dynamic random boundary string118 which is used to compose the body of the request. The random boundary119 string can be explicitly set with the ``multipart_boundary`` parameter.120 """121 if encode_multipart:122 body, content_type = encode_multipart_formdata(123 fields or {}, boundary=multipart_boundary)124 else:125 body, content_type = (urlencode(fields or {}),126 'application/x-www-form-urlencoded')127121 if headers is None:122 headers = self.headers123131 headers_ = {'Content-Type': content_type}132 headers_.update(headers)124 extra_kw = {'headers': {}}125134 return self.urlopen(method, url, body=body, headers=headers_,135 **urlopen_kw)126 if fields:127 if 'body' in urlopen_kw:128 raise TypeError('request got values for both \'fields\' and \'body\', can only specify one.')129130 if encode_multipart:131 body, content_type = encode_multipart_formdata(fields, boundary=multipart_boundary)132 else:133 body, content_type = urlencode(fields), 'application/x-www-form-urlencoded'134135 extra_kw['body'] = body136 extra_kw['headers'] = {'Content-Type': content_type}137138 extra_kw['headers'].update(headers)139 extra_kw.update(urlopen_kw)140141 return self.urlopen(method, url, **extra_kw)
modified:requests/__init__.py+2 added-2 removed
40 unmodified lines
4142"""4344__title__ = 'requests'45__version__ = '2.4.3'46__build__ = 0x02040345__version__ = '2.5.0'46__build__ = 0x02050047__author__ = 'Kenneth Reitz'48__license__ = 'Apache 2.0'49__copyright__ = 'Copyright 2014 Kenneth Reitz'50
27 unmodified lines
modified:requests/adapters.py+13 added-4 removed
24 unmodified lines
25from .packages.urllib3.exceptions import ProxyError as _ProxyError26from .packages.urllib3.exceptions import ProtocolError27from .packages.urllib3.exceptions import ReadTimeoutError28from .packages.urllib3.exceptions import SSLError as _SSLError29from .packages.urllib3.exceptions import ResponseError30from .cookies import extract_cookies_to_jar31from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,31 ProxyError)32 ProxyError, RetryError)33from .auth import _basic_auth_str3435DEFAULT_POOLBLOCK = False36DEFAULT_POOLSIZE = 10
26 unmodified lines
63 :param int max_retries: The maximum number of retries each connection64 should attempt. Note, this applies only to failed DNS lookups, socket65 connections and connection timeouts, never to requests where data has66 made it to the server. By default, Requests does not retry failed66 connections.67 connections. If you need granular control over the conditions under68 which we retry a request, import urllib3's ``Retry`` class and pass69 that instead.70 :param pool_block: Whether the connection pool should block for connections.7172 Usage::73
7 unmodified lines
8182 def __init__(self, pool_connections=DEFAULT_POOLSIZE,83 pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES,84 pool_block=DEFAULT_POOLBLOCK):82 self.max_retries = max_retries85 if max_retries == DEFAULT_RETRIES:86 self.max_retries = Retry(0, read=False)87 else:88 self.max_retries = Retry.from_int(max_retries)89 self.config = {}90 self.proxy_manager = {}9192 super(HTTPAdapter, self).__init__()
272 unmodified lines
365 redirect=False,366 assert_same_host=False,367 preload_content=False,368 decode_content=False,363 retries=Retry(self.max_retries, read=False),369 retries=self.max_retries,370 timeout=timeout371 )372373 # Send the request.
43 unmodified lines
417 except MaxRetryError as e:418 if isinstance(e.reason, ConnectTimeoutError):419 raise ConnectTimeout(e, request=request)420421 if isinstance(e.reason, ResponseError):422 raise RetryError(e, request=request)423424 raise ConnectionError(e, request=request)425426 except _ProxyError as e:427 raise ProxyError(e)
10 unmodified lines
modified:requests/compat.py+1 added-1 removed
74 unmodified lines
7576try:77 import simplejson as json78except (ImportError, SyntaxError):79 # simplejson does not support Python 3.2, it thows a SyntaxError79 # simplejson does not support Python 3.2, it throws a SyntaxError80 # because of u'...' Unicode literals.81 import json8283# ---------
32 unmodified lines
modified:requests/exceptions.py+5 added
88 unmodified lines
8990class ContentDecodingError(RequestException, BaseHTTPError):91 """Failed to decode response content"""929394class StreamConsumedError(RequestException, TypeError):95 """The content for this response was already consumed"""969798class RetryError(RequestException):99 """Custom retries logic failed"""
modified:requests/sessions.py+13 added-4 removed
34 unmodified lines
3536# formerly defined here, reexposed here for backward compatibility37from .models import REDIRECT_STATI3839REDIRECT_CACHE_SIZE = 1000404142def merge_setting(request_setting, session_setting, dict_class=OrderedDict):43 """44 Determines appropriate setting for a given request, taking into account the45 explicit setting on that request, and the setting in the session. If a
84 unmodified lines
130131 # Facilitate relative 'location' headers, as allowed by RFC 7231.132 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')133 # Compliant with RFC3986, we percent encode the url.132 if not urlparse(url).netloc:134 if not parsed.netloc:135 url = urljoin(resp.url, requote_uri(url))136 else:137 url = requote_uri(url)138
136 unmodified lines
275276 __attrs__ = [277 'headers', 'cookies', 'auth', 'proxies', 'hooks', 'params', 'verify',278 'cert', 'prefetch', 'adapters', 'stream', 'trust_env',277 'max_redirects', 'redirect_cache'279 'max_redirects',280 ]281282 def __init__(self):283
46 unmodified lines
330 self.mount('https://', HTTPAdapter())331 self.mount('http://', HTTPAdapter())332333 # Only store 1000 redirects to prevent using infinite memory332 self.redirect_cache = RecentlyUsedContainer(1000)334 self.redirect_cache = RecentlyUsedContainer(REDIRECT_CACHE_SIZE)335336 def __enter__(self):337 return self338
322 unmodified lines
661 for key in keys_to_move:662 self.adapters[key] = self.adapters.pop(key)663664 def __getstate__(self):663 return dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)665 state = dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)666 state['redirect_cache'] = dict(self.redirect_cache)667 return state668669 def __setstate__(self, state):670 redirect_cache = state.pop('redirect_cache', {})671 for attr, value in state.items():672 setattr(self, attr, value)673674 self.redirect_cache = RecentlyUsedContainer(REDIRECT_CACHE_SIZE)675 for redirect, to in redirect_cache.items():676 self.redirect_cache[redirect] = to677678679def session():680 """Returns a :class:`Session` for context-management."""681682 return Session()
modified:requests/utils.py+1 added-1 removed
113 unmodified lines
114115def guess_filename(obj):116 """Tries to guess the filename of the given object."""117 name = getattr(obj, 'name', None)118 if name and name[0] != '<' and name[-1] != '>':118 if name and isinstance(name, builtin_str) and name[0] != '<' and name[-1] != '>':119 return os.path.basename(name)120121122def from_key_val_list(value):
575 unmodified lines
modified:AUTHORS.rst+1 added
156 unmodified lines
157- Martin Jul (`@mjul <https://github.com/mjul>`_)158- Joe Alcorn (`@buttscicles <https://github.com/buttscicles>`_)159- Syed Suhail Ahmed <ssuhail.ahmed93@gmail.com> (`@syedsuhail <https://github.com/syedsuhail>`_)160- Scott Sadler (`@ssadler <https://github.com/ssadler>`_)161- Arthur Darcet (`@arthurdarcet <https://github.com/arthurdarcet>`_)
modified:HISTORY.rst+35 added
1 unmodified line
23Release History4---------------562.5.0 (2014-12-01)7++++++++++++++++++89**Improvements**1011- Allow usage of urllib3's Retry object with HTTPAdapters (#2216)12- The ``iter_lines`` method on a response now accepts a delimiter with which13 to split the content (#2295)1415**Behavioural Changes**1617- Add deprecation warnings to functions in requests.utils that will be removed18 in 3.0 (#2309)19- Sessions used by the functional API are always closed (#2326)20- Restrict requests to HTTP/1.1 and HTTP/1.0 (stop accepting HTTP/0.9) (#2323)2122**Bugfixes**2324- Only parse the URL once (#2353)25- Allow Content-Length header to always be overriden (#2332)26- Properly handle files in HTTPDigestAuth (#2333)27- Cap redirect_cache size to prevent memory abuse (#2299)28- Fix HTTPDigestAuth handling of redirects after authenticating successfully29 (#2253)30- Fix crash with custom method parameter to Session.request (#2317)31- Fix how Link headers are parsed using the regular expression library (#2271)3233**Documentation**3435- Add more references for interlinking (#2348)36- Update CSS for theme (#2290)37- Update width of buttons and sidebar (#2289)38- Replace references of Gittip with Gratipay (#2282)39- Add link to changelog in sidebar (#2273)40412.4.3 (2014-10-06)42++++++++++++++++++4344**Bugfixes**
847 unmodified lines
modified:README.rst+1 added-1 removed
17 unmodified lines
18perform the simplest of tasks.1920Things shouldn't be this way. Not in Python.2122.. code-block:: pycon22.. code-block:: python2324 >>> r = requests.get('https://api.github.com', auth=('user', 'pass'))25 >>> r.status_code26 204
59 unmodified lines
modified:test_requests.py+26 added-6 removed
18 unmodified lines
19 Morsel, cookielib, getproxies, str, urljoin, urlparse, is_py3, builtin_str)20from requests.cookies import cookiejar_from_dict, morsel_to_cookie21from requests.exceptions import (ConnectionError, ConnectTimeout,22 InvalidSchema, InvalidURL, MissingSchema,23 ReadTimeout, Timeout)23 ReadTimeout, Timeout, RetryError)24from requests.models import PreparedRequest25from requests.structures import CaseInsensitiveDict26from requests.sessions import SessionRedirectMixin27from requests.models import urlencode
229 unmodified lines
257 def test_headers_on_session_with_None_are_not_sent(self):258 """Do not send headers in Session.headers with None values."""259 ses = requests.Session()260 ses.headers['Accept-Encoding'] = None261 req = requests.Request('GET', 'http://httpbin.org/get')261 req = requests.Request('GET', httpbin('get'))262 prep = ses.prepare_request(req)263 assert 'Accept-Encoding' not in prep.headers264265 def test_user_agent_transfers(self):
666 unmodified lines
932 p = r.prepare()933934 assert 'multipart/form-data' in p.headers['Content-Type']935936 def test_can_send_file_object_with_non_string_filename(self):937 f = io.BytesIO()938 f.name = 2939 r = requests.Request('POST', httpbin('post'), files={'f': f})940 p = r.prepare()941942 assert 'multipart/form-data' in p.headers['Content-Type']943944 def test_autoset_header_values_are_native(self):945 data = 'this is a string'946 length = '16'947 req = requests.Request('POST', httpbin('post'), data=data)
72 unmodified lines
1020 assert isinstance(s, builtin_str)1021 assert s == "Basic dGVzdDp0ZXN0"10221023 def test_requests_history_is_saved(self):1016 r = requests.get('https://httpbin.org/redirect/5')1024 r = requests.get(httpbin('redirect/5'))1025 total = r.history[-1].history1026 i = 01027 for item in r.history:1028 assert item.history == total[0:i]1021 i=i+11029 i = i + 110301031 def test_json_param_post_content_type_works(self):1032 r = requests.post(1033 httpbin('post'),
328 unmodified lines
13621363class TestTimeout:1364 def test_stream_timeout(self):1365 try:1358 requests.get('https://httpbin.org/delay/10', timeout=2.0)1366 requests.get(httpbin('delay/10'), timeout=2.0)1367 except requests.exceptions.Timeout as e:1368 assert 'Read timed out' in e.args[0].args[0]13691370 def test_invalid_timeout(self):
91 unmodified lines
1462 }14631464 def test_requests_are_updated_each_time(self):1465 session = RedirectSession([303, 307])1458 prep = requests.Request('POST', 'http://httpbin.org/post').prepare()1466 prep = requests.Request('POST', httpbin('post')).prepare()1467 r0 = session.send(prep)1468 assert r0.request.method == 'POST'1469 assert session.calls[-1] == SendCall((r0.request,), {})1470 redirect_generator = session.resolve_redirects(r0, prep)
61 unmodified lines
1532 cookies={'foo': 'bar'}1533 )1534 assert_copy(p, p.copy())153515361537def test_prepare_unicode_url():1538 p = PreparedRequest()1539 p.prepare(1540 method='GET',
1 unmodified line
1542 hooks=[]1543 )1544 assert_copy(p, p.copy())154515461547def test_urllib3_retries():1548 from requests.packages.urllib3.util import Retry1549 s = requests.Session()1550 s.mount('http://', HTTPAdapter(max_retries=Retry(1551 total=2, status_forcelist=[500]1552 )))15531554 with pytest.raises(RetryError):1555 s.get(httpbin('status/500'))15561557if __name__ == '__main__':1558 unittest.main()