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
Provenance
- Commit
39090cf- Tree
b084734- Author
ContinuousFunction <evolutionace@gmail.com>- Committer
ContinuousFunction <evolutionace@gmail.com>- Parent 1
3246b1f- Parent 2
d7c0249
28 files changed+504 added−157 removed
modified:docs/user/advanced.rst+14 added-1 removed
3 unmodified lines4 ==============5 6 This document covers some of Requests more advanced features.7 8+.. _session-objects:9 10 Session Objects11 ---------------12 37 unmodified lines50 51 All values that are contained within a session are directly available to you.52 See the :ref:`Session API Docs <sessionapi>` to learn more.53 54+.. _request-and-response-objects:55+56 Request and Response Objects57 ----------------------------58 59 Whenever a call is made to ``requests.get()`` and friends you are doing two24 unmodified lines84 >>> r.request.headers85 {'Accept-Encoding': 'identity, deflate, compress, gzip',86 'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'}87 88+.. _prepared-requests:89+90 Prepared Requests91 -----------------92 93 Whenever you receive a :class:`Response <requests.Response>` object99 unmodified lines193 194 >>> 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 lib196 197+.. _body-content-workflow:198 199 Body Content Workflow200 ---------------------201 31 unmodified lines233 # Do things with the response here.234 235 .. _`documented here`: http://docs.python.org/2/library/contextlib.html#contextlib.closing236 237+.. _keep-alive:238 239 Keep-Alive240 ----------241 4 unmodified lines246 Note that connections are only released back to the pool for reuse once all body247 data has been read; be sure to either set ``stream`` to ``False`` or read the248 ``content`` property of the ``Response`` object.249 250+.. _streaming-uploads:251 252 Streaming Uploads253 -----------------254 3 unmodified lines258 259 with open('massive-body', 'rb') as f:260 requests.post('http://some.url/streamed', data=f)261 262+.. _chunk-encoding:263 264 Chunk-Encoded Requests265 ----------------------266 8 unmodified lines275 276 requests.post('http://some.url/chunked', data=gen())277 278 279+.. _multipart:280 281 POST Multiple Multipart-Encoded Files282 -------------------------------------283 15 unmodified lines299 'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a',300 ...301 }302 303+.. _event-hooks:304 305 Event Hooks306 -----------307 31 unmodified lines339 >>> requests.get('http://httpbin.org', hooks=dict(response=print_url))340 http://httpbin.org341 <Response [200]>342 343+.. _custom-auth:344 345 Custom Authentication346 ---------------------347 35 unmodified lines383 ------------------384 385 With :class:`requests.Response.iter_lines()` you can easily386 iterate over streaming APIs such as the `Twitter Streaming375-API <https://dev.twitter.com/docs/streaming-api>`_. Simply387+API <https://dev.twitter.com/streaming/overview>`_. Simply388 set ``stream`` to ``True`` and iterate over the response with389 :class:`~requests.Response.iter_lines()`::390 391 import json6 unmodified lines398 # filter out keep-alive new lines399 if line:400 print(json.loads(line))401 402+.. _proxies:403 404 Proxies405 -------406 392 unmodified linesmodified:requests/packages/chardet/__init__.py+1 added-1 removed
13 unmodified lines14 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA15 # 02110-1301 USA16 ######################### END LICENSE BLOCK #########################17 18-__version__ = "2.2.1"18+__version__ = "2.3.0"19 from sys import version_info20 21 22 def detect(aBuf):10 unmodified linesmodified:requests/packages/chardet/chardetect.py+49 added-15 removed
10 unmodified lines11 12 If no paths are provided, it takes its input from stdin.13 14 """15+16+from __future__ import absolute_import, print_function, unicode_literals17+18+import argparse19+import sys20 from io import open16-from sys import argv, stdin21 22+from chardet import __version__23 from chardet.universaldetector import UniversalDetector24 25 21-def description_of(file, name='stdin'):22- """Return a string describing the probable encoding of a file."""26+def description_of(lines, name='stdin'):27+ """28+ Return a string describing the probable encoding of a file or29+ list of strings.30+31+ :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)46 47 36-def 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))48+def main(argv=None):49+ '''50+ Handles command line arguments and gets things started.51 52+ :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)69 70+ 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))77+78+79 if __name__ == '__main__':80 main()modified:requests/packages/chardet/jpcntx.py+8 added
175 unmodified lines176 def get_order(self, aBuf):177 return -1, 1178 179 class SJISContextAnalysis(JapaneseContextAnalysis):180+ def __init__(self):181+ self.charset_name = "SHIFT_JIS"182+183+ def get_charset_name(self):184+ return self.charset_name185+186 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 = 1197 198 # return its order if it is hiragana29 unmodified linesmodified:requests/packages/chardet/latin1prober.py+3 added-3 removed
127 unmodified lines128 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 confidencemodified:requests/packages/chardet/mbcssm.py+3 added-6 removed
351 unmodified lines352 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 does7 unmodified lines368 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 - ff374 375 376 SJIS_st = (377 eError,eStart,eStart, 3,eError,eError,eError,eError,#00-07191 unmodified lines569 'classFactor': 16,570 'stateTable': UTF8_st,571 'charLenTable': UTF8CharLenTable,572 'name': 'UTF-8'}574-575-# flake8: noqamodified:requests/packages/chardet/sjisprober.py+1 added-1 removed
45 unmodified lines46 MultiByteCharSetProber.reset(self)47 self._mContextAnalyzer.reset()48 49 def get_charset_name(self):50- return "SHIFT_JIS"50+ return self._mContextAnalyzer.get_charset_name()51 52 def feed(self, aBuf):53 aLen = len(aBuf)54 for i in range(0, aLen):37 unmodified linesmodified:requests/packages/chardet/universaldetector.py+2 added-2 removed
69 unmodified lines70 return71 72 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 linesmodified:requests/packages/urllib3/contrib/pyopenssl.py+22 added-3 removed
27 unmodified lines28 Now you can use :mod:`urllib3` as you normally would, and it will support SNI29 when the required modules are installed.30 31 Activating this module also has the positive side effect of disabling SSL/TLS32-encryption in Python 2 (see `CRIME attack`_).32+compression in Python 2 (see `CRIME attack`_).33 34 If you want to configure the default list of supported cipher suites, you can35 set the ``urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST`` variable.36 32 unmodified lines69 70 # 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 }75+76+try:77+ _openssl_versions.update({ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD})78+except AttributeError:79+ pass80+81 _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_PEER118 unmodified lines203 204 def settimeout(self, timeout):205 return self.socket.settimeout(timeout)206 207+ 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+ continue217+218 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:]222 223 def close(self):224 if self._makefile_refs < 1:225 return self.connection.shutdown()39 unmodified lines265 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 linesmodified:requests/packages/urllib3/util/retry.py+15 added-9 removed
1 import time2 import logging3 4 from ..exceptions import (5- ProtocolError,5 ConnectTimeoutError,7- ReadTimeoutError,6 MaxRetryError,7+ ProtocolError,8+ ReadTimeoutError,9+ ResponseError,10 )11 from ..packages import six12 13 22 unmodified lines36 37 Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless38 retries are disabled, in which case the causing exception will be raised.39 39-40 :param int total:41 Total number of retries to allow. Takes precedence over other counts.42 43 Set to ``None`` to remove this constraint and fall back on other139 unmodified lines183 """184 return isinstance(err, ConnectTimeoutError)185 186 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))191 192 def is_forced_retry(self, method, status_code):4 unmodified lines197 198 return self.status_forcelist and status_code in self.status_forcelist199 200 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 False22 unmodified lines228 _observed_errors = self._observed_errors229 connect = self.connect230 read = self.read231 redirect = self.redirect232+ cause = 'unknown'233 234 if error and self._is_connection_error(error):235 # Connect retry?236 if connect is False:13 unmodified lines250 elif response and response.get_redirect_location():251 # Redirect retry?252 if redirect is not None:253 redirect -= 1254+ cause = 'too many redirects'255 256 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)264 265 new_retry = self.new(266 total=total,267 connect=connect, read=read, redirect=redirect,268 _observed_errors=_observed_errors)269 270 if new_retry.is_exhausted():265- raise MaxRetryError(_pool, url, error)271+ raise MaxRetryError(_pool, url, error or ResponseError(cause))272 273 log.debug("Incremented Retry for (url='%s'): %r" % (url, new_retry))274 275 return new_retry10 unmodified linesmodified:requests/packages/urllib3/util/ssl_.py+162 added-40 removed
2 unmodified lines3 4 from ..exceptions import SSLError5 6 7-try: # Test for SSL features8- SSLContext = None9- HAS_SNI = False7+SSLContext = None8+HAS_SNI = False9+create_default_context = None10 11- import ssl11+import errno12+import ssl13+14+try: # 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?17 except ImportError:18 pass19 20 21+try:22+ from ssl import OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION23+except ImportError:24+ OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x200000025+ OP_NO_COMPRESSION = 0x2000026+27+try:28+ from ssl import _DEFAULT_CIPHERS29+except 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+ )35+36+try:37+ from ssl import SSLContext # Modern SSL?38+except ImportError:39+ import sys40+41+ class SSLContext(object): # Platform-specific: Python 2 & 3.142+ supports_set_ciphers = sys.version_info >= (2, 7)43+44+ 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 = None54+55+ def load_cert_chain(self, certfile, keyfile):56+ self.certfile = certfile57+ self.keyfile = keyfile58+59+ def load_verify_locations(self, location):60+ self.ca_certs = location61+62+ 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_suite70+71+ 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)83+84+85 def assert_fingerprint(cert, fingerprint):86 """87 Checks if given fingerprint matches the supplied certificate.88 67 unmodified lines156 157 return candidate158 159 94-if 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`160+def 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``.163 102- :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:166 108- # 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 ciphers169 112- 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::171 126-else: # 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_SSLv3175+176+ You can do the same to enable compression (substituting ``COMPRESSION``177+ for ``SSLv3`` in the last line above).178+179+ :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)196+197+ 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_COMPRESSION206+207+ context.options |= options208+209+ if getattr(context, 'supports_set_ciphers', True): # Platform-specific: Python 2.6210+ context.set_ciphers(ciphers or _DEFAULT_CIPHERS)211+212+ 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 context216+217+218+def 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`.224+225+ :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)238+239+ 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 lines39 if self.port:40 return '%s:%d' % (self.host, self.port)41 return self.host42 43+ @property44+ def url(self):45+ """46+ Convert self into a url47 48+ 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).52+53+ Example: ::54+55+ >>> 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 = ''64+65+ # 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 += '#' + fragment80+81+ return url82+83+ def __str__(self):84+ return self.url85+86 def 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 lines125 126 Example::127 128 >>> 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 lines203 path, query = path.split('?', 1)204 205 return Url(scheme, auth, host, port, path, query, fragment)206 165-207 def get_host(url):208 """209 Deprecated. Use :func:`.parse_url` instead.210 """2 unmodified linesmodified:requests/packages/urllib3/__init__.py+1 added-1 removed
55 unmodified lines56 57 58 # Set security warning to only go off once by default.59 import warnings60-warnings.simplefilter('module', exceptions.SecurityWarning)60+warnings.simplefilter('always', exceptions.SecurityWarning)61 62 def disable_warnings(category=exceptions.HTTPWarning):63 """64 Helper for quickly disabling all urllib3 warnings.2 unmodified linesmodified:requests/packages/urllib3/_collections.py+3 added-4 removed
12 unmodified lines13 try: # Python 2.7+14 from collections import OrderedDict15 except ImportError:16 from .packages.ordered_dict import OrderedDict17-from .packages.six import itervalues17+from .packages.six import iterkeys, itervalues18 19 20 __all__ = ['RecentlyUsedContainer', 'HTTPHeaderDict']21 62 unmodified lines84 85 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()90 91 if self.dispose_func:92 for value in values:93 self.dispose_func(value)94 95 def keys(self):96 with self.lock:98- return self._container.keys()97+ return list(iterkeys(self._container))98 99 100 class HTTPHeaderDict(MutableMapping):101 """97 unmodified linesmodified:requests/packages/urllib3/connection.py+20 added-4 removed
1 unmodified line2 import sys3 import socket4 from socket import timeout as SocketTimeout5 import warnings6+from .packages import six7 8 try: # Python 39 from http.client import HTTPConnection as _HTTPConnection, HTTPException10 except ImportError:15 unmodified lines26 class BaseSSLError(BaseException):27 pass28 29 30+try: # Python 3:31+ # Not a no-op, we're adding this to the namespace so it can be imported.32+ ConnectionError = ConnectionError33+except NameError: # Python 2:34+ class ConnectionError(Exception):35+ pass36+37+38 from .exceptions import (39 ConnectTimeoutError,40 SystemTimeWarning,41+ SecurityWarning,42 )43 from .packages.ssl_match_hostname import match_hostname34-from .packages import six44 45 from .util.ssl_ import (46 resolve_cert_reqs,47 resolve_ssl_version,48 ssl_wrap_socket,49 assert_fingerprint,50 )51 52+53 from .util import connection54 45-55 port_by_scheme = {56 'http': 80,57 'https': 443,58 }182 unmodified lines241 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)254 255 self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED256 or self.assert_fingerprint is not None)257 5 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+34 added-30 removed
30 unmodified lines31 from .connection import (32 port_by_scheme,33 DummyConnection,34 HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,35- HTTPException, BaseSSLError,35+ HTTPException, BaseSSLError, ConnectionError36 )37 from .request import RequestMethods38 from .response import HTTPResponse39 237 unmodified lines277 # User passed us an int/float. This is for backwards compatibility,278 # can be removed later279 return Timeout.from_float(timeout)280 281+ def _raise_timeout(self, err, url, timeout_value):282+ """Is the error actually a timeout? Will raise a ReadTimeout or pass"""283+284+ if isinstance(err, SocketTimeout):285+ raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)286+287+ # 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)291+292+ # 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)297+298 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 our15 unmodified lines317 timeout_obj.start_connect()318 conn.timeout = timeout_obj.connect_timeout319 320 # 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+ raise327 328 # 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 lines352 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)337-338- 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)346-356+ except (SocketTimeout, BaseSSLError, SocketError) as e:357+ self._raise_timeout(err=e, url=url, timeout_value=read_timeout)358 raise359 349- 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)355-356- raise357-360 # 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 lines538 # Timed out by queue.539 raise EmptyPoolError(self, "No pool connections are available.")540 541 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)549 545- 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 lines729 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)735 736 737 def connection_from_url(url, **kw):24 unmodified linesmodified:requests/packages/urllib3/exceptions.py+8 added-5 removed
70 unmodified lines71 72 def __init__(self, pool, url, reason=None):73 self.reason = reason74 75- 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)77 78 RequestError.__init__(self, pool, url, message)79 80 56 unmodified lines137 138 self.location = location139 140 141+class 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'145+146+147 class SecurityWarning(HTTPWarning):148 "Warned when perfoming security reducing actions"149 pass150 9 unmodified linesmodified:requests/packages/urllib3/request.py+17 added-11 removed
116 unmodified lines117 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')127-121 if headers is None:122 headers = self.headers123 131- headers_ = {'Content-Type': content_type}132- headers_.update(headers)124+ extra_kw = {'headers': {}}125 134- 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.')129+130+ 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'134+135+ extra_kw['body'] = body136+ extra_kw['headers'] = {'Content-Type': content_type}137+138+ extra_kw['headers'].update(headers)139+ extra_kw.update(urlopen_kw)140+141+ return self.urlopen(method, url, **extra_kw)modified:requests/__init__.py+2 added-2 removed
40 unmodified lines41 42 """43 44 __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 linesmodified:requests/adapters.py+13 added-4 removed
24 unmodified lines25 from .packages.urllib3.exceptions import ProxyError as _ProxyError26 from .packages.urllib3.exceptions import ProtocolError27 from .packages.urllib3.exceptions import ReadTimeoutError28 from .packages.urllib3.exceptions import SSLError as _SSLError29+from .packages.urllib3.exceptions import ResponseError30 from .cookies import extract_cookies_to_jar31 from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,31- ProxyError)32+ ProxyError, RetryError)33 from .auth import _basic_auth_str34 35 DEFAULT_POOLBLOCK = False36 DEFAULT_POOLSIZE = 1026 unmodified lines63 :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.71 72 Usage::73 7 unmodified lines81 82 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 = {}91 92 super(HTTPAdapter, self).__init__()272 unmodified lines365 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 )372 373 # Send the request.43 unmodified lines417 except MaxRetryError as e:418 if isinstance(e.reason, ConnectTimeoutError):419 raise ConnectTimeout(e, request=request)420 421+ if isinstance(e.reason, ResponseError):422+ raise RetryError(e, request=request)423+424 raise ConnectionError(e, request=request)425 426 except _ProxyError as e:427 raise ProxyError(e)10 unmodified linesmodified:requests/compat.py+1 added-1 removed
74 unmodified lines75 76 try:77 import simplejson as json78 except (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 json82 83 # ---------32 unmodified linesmodified:requests/exceptions.py+5 added
88 unmodified lines89 90 class ContentDecodingError(RequestException, BaseHTTPError):91 """Failed to decode response content"""92 93+94 class StreamConsumedError(RequestException, TypeError):95 """The content for this response was already consumed"""96+97+98+class RetryError(RequestException):99+ """Custom retries logic failed"""modified:requests/sessions.py+13 added-4 removed
34 unmodified lines35 36 # formerly defined here, reexposed here for backward compatibility37 from .models import REDIRECT_STATI38 39+REDIRECT_CACHE_SIZE = 100040 41+42 def 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 a84 unmodified lines130 131 # 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 lines275 276 __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 ]281 282 def __init__(self):283 46 unmodified lines330 self.mount('https://', HTTPAdapter())331 self.mount('http://', HTTPAdapter())332 333 # Only store 1000 redirects to prevent using infinite memory332- self.redirect_cache = RecentlyUsedContainer(1000)334+ self.redirect_cache = RecentlyUsedContainer(REDIRECT_CACHE_SIZE)335 336 def __enter__(self):337 return self338 322 unmodified lines661 for key in keys_to_move:662 self.adapters[key] = self.adapters.pop(key)663 664 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 state668 669 def __setstate__(self, state):670+ redirect_cache = state.pop('redirect_cache', {})671 for attr, value in state.items():672 setattr(self, attr, value)673 674+ self.redirect_cache = RecentlyUsedContainer(REDIRECT_CACHE_SIZE)675+ for redirect, to in redirect_cache.items():676+ self.redirect_cache[redirect] = to677 678+679 def session():680 """Returns a :class:`Session` for context-management."""681 682 return Session()modified:requests/utils.py+1 added-1 removed
113 unmodified lines114 115 def 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)120 121 122 def from_key_val_list(value):575 unmodified linesmodified:AUTHORS.rst+1 added
156 unmodified lines157 - 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 line2 3 Release History4 ---------------5 6+2.5.0 (2014-12-01)7+++++++++++++++++++8+9+**Improvements**10+11+- 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)14+15+**Behavioural Changes**16+17+- 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)21+22+**Bugfixes**23+24+- 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)32+33+**Documentation**34+35+- 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)40+41 2.4.3 (2014-10-06)42 ++++++++++++++++++43 44 **Bugfixes**847 unmodified linesmodified:README.rst+1 added-1 removed
17 unmodified lines18 perform the simplest of tasks.19 20 Things shouldn't be this way. Not in Python.21 22-.. code-block:: pycon22+.. code-block:: python23 24 >>> r = requests.get('https://api.github.com', auth=('user', 'pass'))25 >>> r.status_code26 20459 unmodified linesmodified:test_requests.py+26 added-6 removed
18 unmodified lines19 Morsel, cookielib, getproxies, str, urljoin, urlparse, is_py3, builtin_str)20 from requests.cookies import cookiejar_from_dict, morsel_to_cookie21 from requests.exceptions import (ConnectionError, ConnectTimeout,22 InvalidSchema, InvalidURL, MissingSchema,23- ReadTimeout, Timeout)23+ ReadTimeout, Timeout, RetryError)24 from requests.models import PreparedRequest25 from requests.structures import CaseInsensitiveDict26 from requests.sessions import SessionRedirectMixin27 from requests.models import urlencode229 unmodified lines257 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.headers264 265 def test_user_agent_transfers(self):666 unmodified lines932 p = r.prepare()933 934 assert 'multipart/form-data' in p.headers['Content-Type']935 936+ 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()941+942+ assert 'multipart/form-data' in p.headers['Content-Type']943+944 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 lines1020 assert isinstance(s, builtin_str)1021 assert s == "Basic dGVzdDp0ZXN0"1022 1023 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 + 11030 1031 def test_json_param_post_content_type_works(self):1032 r = requests.post(1033 httpbin('post'),328 unmodified lines1362 1363 class 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]1369 1370 def test_invalid_timeout(self):91 unmodified lines1462 }1463 1464 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 lines1532 cookies={'foo': 'bar'}1533 )1534 assert_copy(p, p.copy())1535 1536+1537 def test_prepare_unicode_url():1538 p = PreparedRequest()1539 p.prepare(1540 method='GET',1 unmodified line1542 hooks=[]1543 )1544 assert_copy(p, p.copy())1545 1546+1547+def 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+ )))1553+1554+ with pytest.raises(RetryError):1555+ s.get(httpbin('status/500'))1556+1557 if __name__ == '__main__':1558 unittest.main()