Skip to content
Myr

urllib3 v1.3

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 · parent afb1bd1 · Browse files · 7 files+190 added−162 removed
This commit

State

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

Diff stats

7 files+190 added−162 removed

  • other:+190 added−162 removed

7 files+190 added−162 removed

modified:requests/packages/urllib3/__init__.py+6 added-12 removed
8 unmodified lines
9"""1011__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'12__license__ = 'MIT'13__version__ = '1.2.2'13__version__ = '1.3'141516from .connectionpool import (17 HTTPConnectionPool,18 HTTPSConnectionPool,19 connection_from_url,20 get_host,21 make_headers)19 connection_from_url20)212324from .exceptions import (25 HTTPError,26 MaxRetryError,27 SSLError,28 TimeoutError)2922from . import exceptions23from .filepost import encode_multipart_formdata24from .poolmanager import PoolManager, ProxyManager, proxy_from_url25from .response import HTTPResponse32from .filepost import encode_multipart_formdata26from .util import make_headers, get_host272829# Set default logging handler to avoid "No handler found" warnings.30import logging
12 unmodified lines
modified:requests/packages/urllib3/connectionpool.py+13 added-121 removed
5 unmodified lines
67import logging8import socket910from base64 import b64encode10from socket import error as SocketError, timeout as SocketTimeout1113try:14 from select import poll, POLLIN15except ImportError: # Doesn't exist on OSX and other platforms16 from select import select17 poll = False1812try: # Python 313 from http.client import HTTPConnection, HTTPException14 from http.client import HTTP_PORT, HTTPS_PORT15except ImportError:
18 unmodified lines
3435 import ssl36 BaseSSLError = ssl.SSLError3745except ImportError:38except (ImportError, AttributeError):39 pass404149from .packages.ssl_match_hostname import match_hostname, CertificateError42from .request import RequestMethods43from .response import HTTPResponse44from .util import get_host, is_connection_dropped45from .exceptions import (46 EmptyPoolError,47 HostChangedError,55 LocationParseError,48 MaxRetryError,49 SSLError,50 TimeoutError,51)5253from .packages.ssl_match_hostname import match_hostname, CertificateError54from .packages import six555657xrange = six.moves.xrange5859log = logging.getLogger(__name__)60
3 unmodified lines
64 'http': HTTP_PORT,65 'https': HTTPS_PORT,66}676869## Connection objects (extension of httplib)7071class VerifiedHTTPSConnection(HTTPSConnection):72 """
27 unmodified lines
100 ca_certs=self.ca_certs)101 if self.ca_certs:102 match_hostname(self.sock.getpeercert(), self.host)103104105## Pool objects106107class ConnectionPool(object):108 """
97 unmodified lines
206 try:207 conn = self.pool.get(block=self.block, timeout=timeout)208209 # If this is a persistent connection, check if it got disconnected215 if conn and conn.sock and is_connection_dropped(conn):210 if conn and is_connection_dropped(conn):211 log.info("Resetting dropped connection: %s" % self.host)212 conn.close()213214 except Empty:
35 unmodified lines
250 if timeout is _Default:251 timeout = self.timeout252253 conn.timeout = timeout # This only does anything in Py26+259254 conn.request(method, url, **httplib_request_kw)255256 # Set timeout257 sock = getattr(conn, 'sock', False) # AppEngine doesn't have sock attr.258 if sock:261 conn.sock.settimeout(timeout)259 sock.settimeout(timeout)260261 httplib_response = conn.getresponse()262263 log.debug("\"%s %s %s\" %s %s" %264 (method, url,
28 unmodified lines
293294 .. note::295296 More commonly, it's appropriate to use a convenience method provided298 by :class:`.RequestMethods`, such as :meth:`.request`.297 by :class:`.RequestMethods`, such as :meth:`request`.298299 .. note::300301 `release_conn` will only behave as expected if
191 unmodified lines
493 cert_reqs=self.cert_reqs, ca_certs=self.ca_certs)494 return connection495496498## Helpers499500def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,501 basic_auth=None):502 """503 Shortcuts for generating request headers.504505 :param keep_alive:506 If ``True``, adds 'connection: keep-alive' header.507508 :param accept_encoding:509 Can be a boolean, list, or string.510 ``True`` translates to 'gzip,deflate'.511 List will get joined by comma.512 String will be used as provided.513514 :param user_agent:515 String representing the user-agent you want, such as516 "python-urllib3/0.6"517518 :param basic_auth:519 Colon-separated username:password string for 'authorization: basic ...'520 auth header.521522 Example: ::523524 >>> make_headers(keep_alive=True, user_agent="Batman/1.0")525 {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}526 >>> make_headers(accept_encoding=True)527 {'accept-encoding': 'gzip,deflate'}528 """529 headers = {}530 if accept_encoding:531 if isinstance(accept_encoding, str):532 pass533 elif isinstance(accept_encoding, list):534 accept_encoding = ','.join(accept_encoding)535 else:536 accept_encoding = 'gzip,deflate'537 headers['accept-encoding'] = accept_encoding538539 if user_agent:540 headers['user-agent'] = user_agent541542 if keep_alive:543 headers['connection'] = 'keep-alive'544545 if basic_auth:546 headers['authorization'] = 'Basic ' + \547 b64encode(six.b(basic_auth)).decode('utf-8')548549 return headers550551552def get_host(url):553 """554 Given a url, return its scheme, host and port (None if it's not there).555556 For example: ::557558 >>> get_host('http://google.com/mail/')559 ('http', 'google.com', None)560 >>> get_host('google.com:80')561 ('http', 'google.com', 80)562 """563564 # This code is actually similar to urlparse.urlsplit, but much565 # simplified for our needs.566 port = None567 scheme = 'http'568569 if '://' in url:570 scheme, url = url.split('://', 1)571 if '/' in url:572 url, _path = url.split('/', 1)573 if '@' in url:574 _auth, url = url.split('@', 1)575 if ':' in url:576 url, port = url.split(':', 1)577578 if not port.isdigit():579 raise LocationParseError("Failed to parse: %s")580581 port = int(port)582583 return scheme, url, port584585497def connection_from_url(url, **kw):498 """499 Given a url, return an :class:`.ConnectionPool` instance of its host.500
17 unmodified lines
518 if scheme == 'https':519 return HTTPSConnectionPool(host, port=port, **kw)520 else:521 return HTTPConnectionPool(host, port=port, **kw)611612613def is_connection_dropped(conn):614 """615 Returns True if the connection is dropped and should be closed.616617 :param conn:618 ``HTTPConnection`` object.619 """620 if not poll: # Platform-specific621 return select([conn.sock], [], [], 0.0)[0]622623 # This version is better on platforms that support it.624 p = poll()625 p.register(conn.sock, POLLIN)626 for (fno, ev) in p.poll(0.0):627 if fno == conn.sock.fileno():628 # Either data is buffered (bad), or the connection is dropped.629 return True
modified:requests/packages/urllib3/filepost.py+19 added-5 removed
22 unmodified lines
23def get_content_type(filename):24 return mimetypes.guess_type(filename)[0] or 'application/octet-stream'252627def iter_fields(fields):28 """29 Iterate over fields.3031 Supports list of (k, v) tuples and dicts.32 """33 if isinstance(fields, dict):34 return ((k, v) for k, v in six.iteritems(fields))3536 return ((k, v) for k, v in fields)373839def encode_multipart_formdata(fields, boundary=None):40 """41 Encode a dictionary of ``fields`` using the multipart/form-data mime format.4243 :param fields:32 Dictionary of fields. The key is treated as the field name, and the33 value as the body of the form-data. If the value is a tuple of two34 elements, then the first element is treated as the filename of the35 form-data section.44 Dictionary of fields or list of (key, value) field tuples. The key is45 treated as the field name, and the value as the body of the form-data46 bytes. If the value is a tuple of two elements, then the first element47 is treated as the filename of the form-data section.4849 Field names and filenames must be unicode.5051 :param boundary:52 If not specified, then a random boundary will be generated using53 :func:`mimetools.choose_boundary`.54 """55 body = BytesIO()56 if boundary is None:57 boundary = choose_boundary()5845 for fieldname, value in six.iteritems(fields):59 for fieldname, value in iter_fields(fields):60 body.write(b('--%s\r\n' % (boundary)))6162 if isinstance(value, tuple):63 filename, data = value
25 unmodified lines
modified:requests/packages/urllib3/poolmanager.py+2 added-2 removed
37 unmodified lines
38 :class:`urllib3.connectionpool.ConnectionPool` instances.3940 Example: ::4142 >>> manager = PoolManager()42 >>> manager = PoolManager(num_pools=2)43 >>> r = manager.urlopen("http://google.com/")44 >>> r = manager.urlopen("http://google.com/mail")45 >>> r = manager.urlopen("http://yahoo.com/")46 >>> len(r.pools)46 >>> len(manager.pools)47 24849 """50
88 unmodified lines
modified:requests/packages/urllib3/request.py+1 added-20 removed
42 unmodified lines
43 _encode_body_methods = set(['PATCH', 'POST', 'PUT', 'TRACE'])4445 def urlopen(self, method, url, body=None, headers=None,46 encode_multipart=True, multipart_boundary=None,47 **kw):47 **kw): # Abstract48 raise NotImplemented("Classes extending RequestMethods must implement "49 "their own ``urlopen`` method.")5051 def request(self, method, url, fields=None, headers=None, **urlopen_kw):
73 unmodified lines
125 headers.update({'Content-Type': content_type})126127 return self.urlopen(method, url, body=body, headers=headers,128 **urlopen_kw)129130 # Deprecated:131132 def get_url(self, url, fields=None, **urlopen_kw):133 """134 .. deprecated:: 1.0135 Use :meth:`request` instead.136 """137 return self.request_encode_url('GET', url, fields=fields,138 **urlopen_kw)139140 def post_url(self, url, fields=None, headers=None, **urlopen_kw):141 """142 .. deprecated:: 1.0143 Use :meth:`request` instead.144 """145 return self.request_encode_body('POST', url, fields=fields,146 headers=headers,147 **urlopen_kw)
modified:requests/packages/urllib3/response.py+13 added-2 removed
169 unmodified lines
170 Remaining parameters are passed to the HTTPResponse constructor, along171 with ``original_response=r``.172 """173174 # Normalize headers between different versions of Python175 headers = {}176 for k, v in r.getheaders():177 # Python 3: Header keys are returned capitalised178 k = k.lower()179180 has_value = headers.get(k)181 if has_value: # Python 3: Repeating header keys are unmerged.182 v = ', '.join([has_value, v])183184 headers[k] = v185186 # HTTPResponse objects in Python 3 don't have a .strict attribute187 strict = getattr(r, 'strict', 0)188 return ResponseCls(body=r,177 # In Python 3, the header keys are returned capitalised178 headers=dict((k.lower(), v) for k,v in r.getheaders()),189 headers=headers,190 status=r.status,191 version=r.version,192 reason=r.reason,193 strict=strict,
9 unmodified lines
added:requests/packages/urllib3/util.py+136 added
1# urllib3/util.py2# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php678from base64 import b64encode910try:11 from select import poll, POLLIN12except ImportError: # `poll` doesn't exist on OSX and other platforms13 poll = False14 try:15 from select import select16 except ImportError: # `select` doesn't exist on AppEngine.17 select = False1819from .packages import six20from .exceptions import LocationParseError212223def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,24 basic_auth=None):25 """26 Shortcuts for generating request headers.2728 :param keep_alive:29 If ``True``, adds 'connection: keep-alive' header.3031 :param accept_encoding:32 Can be a boolean, list, or string.33 ``True`` translates to 'gzip,deflate'.34 List will get joined by comma.35 String will be used as provided.3637 :param user_agent:38 String representing the user-agent you want, such as39 "python-urllib3/0.6"4041 :param basic_auth:42 Colon-separated username:password string for 'authorization: basic ...'43 auth header.4445 Example: ::4647 >>> make_headers(keep_alive=True, user_agent="Batman/1.0")48 {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}49 >>> make_headers(accept_encoding=True)50 {'accept-encoding': 'gzip,deflate'}51 """52 headers = {}53 if accept_encoding:54 if isinstance(accept_encoding, str):55 pass56 elif isinstance(accept_encoding, list):57 accept_encoding = ','.join(accept_encoding)58 else:59 accept_encoding = 'gzip,deflate'60 headers['accept-encoding'] = accept_encoding6162 if user_agent:63 headers['user-agent'] = user_agent6465 if keep_alive:66 headers['connection'] = 'keep-alive'6768 if basic_auth:69 headers['authorization'] = 'Basic ' + \70 b64encode(six.b(basic_auth)).decode('utf-8')7172 return headers737475def get_host(url):76 """77 Given a url, return its scheme, host and port (None if it's not there).7879 For example: ::8081 >>> get_host('http://google.com/mail/')82 ('http', 'google.com', None)83 >>> get_host('google.com:80')84 ('http', 'google.com', 80)85 """8687 # This code is actually similar to urlparse.urlsplit, but much88 # simplified for our needs.89 port = None90 scheme = 'http'9192 if '://' in url:93 scheme, url = url.split('://', 1)94 if '/' in url:95 url, _path = url.split('/', 1)96 if '@' in url:97 _auth, url = url.split('@', 1)98 if ':' in url:99 url, port = url.split(':', 1)100101 if not port.isdigit():102 raise LocationParseError("Failed to parse: %s" % url)103104 port = int(port)105106 return scheme, url, port107108109110def is_connection_dropped(conn):111 """112 Returns True if the connection is dropped and should be closed.113114 :param conn:115 ``HTTPConnection`` object.116117 Note: For platforms like AppEngine, this will always return ``False`` to118 let the platform handle connection recycling transparently for us.119 """120 sock = getattr(conn, 'sock', False)121 if not sock: #Platform-specific: AppEngine122 return False123124 if not poll: # Platform-specific125 if not select: #Platform-specific: AppEngine126 return False127128 return select([sock], [], [], 0.0)[0]129130 # This version is better on platforms that support it.131 p = poll()132 p.register(sock, POLLIN)133 for (fno, ev) in p.poll(0.0):134 if fno == sock.fileno():135 # Either data is buffered (bad), or the connection is dropped.136 return True