Import urllib3
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 95336a0 · Browse files · 10 files·+1370 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+1370 added−0 removed
- other:+1370 added−0 removed
Provenance
- Commit
7c271a4- Tree
89cf955- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
95336a0
10 files changed+1370 added−0 removed
added:requests/packages/urllib3/contrib/__init__.py
added:requests/packages/urllib3/contrib/ntlmpool.py+117 added
1+# urllib3/contrib/ntlmpool.py2+# Copyright 2008-2011 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.php6+7+"""8+NTLM authenticating pool, contributed by erikcederstran9+10+Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=1011+"""12+13+import httplib14+from logging import getLogger15+from ntlm import ntlm16+17+from urllib3 import HTTPSConnectionPool18+19+20+log = getLogger(__name__)21+22+23+class NTLMConnectionPool(HTTPSConnectionPool):24+ """25+ Implements an NTLM authentication version of an urllib3 connection pool26+ """27+28+ scheme = 'https'29+30+ def __init__(self, user, pw, authurl, *args, **kwargs):31+ """32+ authurl is a random URL on the server that is protected by NTLM.33+ user is the Windows user, probably in the DOMAIN\username format.34+ pw is the password for the user.35+ """36+ super(NTLMConnectionPool, self).__init__(*args, **kwargs)37+ self.authurl = authurl38+ self.rawuser = user39+ user_parts = user.split('\\', 1)40+ self.domain = user_parts[0].upper()41+ self.user = user_parts[1]42+ self.pw = pw43+44+ def _new_conn(self):45+ # Performs the NTLM handshake that secures the connection. The socket46+ # must be kept open while requests are performed.47+ self.num_connections += 148+ log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s' %49+ (self.num_connections, self.host, self.authurl))50+51+ headers = {}52+ headers['Connection'] = 'Keep-Alive'53+ req_header = 'Authorization'54+ resp_header = 'www-authenticate'55+56+ conn = httplib.HTTPSConnection(host=self.host, port=self.port)57+58+ # Send negotiation message59+ headers[req_header] = (60+ 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser))61+ log.debug('Request headers: %s' % headers)62+ conn.request('GET', self.authurl, None, headers)63+ res = conn.getresponse()64+ reshdr = dict(res.getheaders())65+ log.debug('Response status: %s %s' % (res.status, res.reason))66+ log.debug('Response headers: %s' % reshdr)67+ log.debug('Response data: %s [...]' % res.read(100))68+69+ # Remove the reference to the socket, so that it can not be closed by70+ # the response object (we want to keep the socket open)71+ res.fp = None72+73+ # Server should respond with a challenge message74+ auth_header_values = reshdr[resp_header].split(', ')75+ auth_header_value = None76+ for s in auth_header_values:77+ if s[:5] == 'NTLM ':78+ auth_header_value = s[5:]79+ if auth_header_value is None:80+ raise Exception('Unexpected %s response header: %s' %81+ (resp_header, reshdr[resp_header]))82+83+ # Send authentication message84+ ServerChallenge, NegotiateFlags = \85+ ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value)86+ auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge,87+ self.user,88+ self.domain,89+ self.pw,90+ NegotiateFlags)91+ headers[req_header] = 'NTLM %s' % auth_msg92+ log.debug('Request headers: %s' % headers)93+ conn.request('GET', self.authurl, None, headers)94+ res = conn.getresponse()95+ log.debug('Response status: %s %s' % (res.status, res.reason))96+ log.debug('Response headers: %s' % dict(res.getheaders()))97+ log.debug('Response data: %s [...]' % res.read()[:100])98+ if res.status != 200:99+ if res.status == 401:100+ raise Exception('Server rejected request: wrong '101+ 'username or password')102+ raise Exception('Wrong server response: %s %s' %103+ (res.status, res.reason))104+105+ res.fp = None106+ log.debug('Connection established')107+ return conn108+109+ def urlopen(self, method, url, body=None, headers=None, retries=3,110+ redirect=True, assert_same_host=True):111+ if headers is None:112+ headers = {}113+ headers['Connection'] = 'Keep-Alive'114+ return super(NTLMConnectionPool, self).urlopen(method, url, body,115+ headers, retries,116+ redirect,117+ assert_same_host)added:requests/packages/urllib3/__init__.py+48 added
1+# urllib3/__init__.py2+# Copyright 2008-2011 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.php6+7+"""8+urllib3 - Thread-safe connection pooling and re-using.9+"""10+11+__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'12+__license__ = 'MIT'13+__version__ = '1.0.1'14+15+16+from .connectionpool import (17+ HTTPConnectionPool,18+ HTTPSConnectionPool,19+ connection_from_url,20+ get_host,21+ make_headers)22+23+24+from .exceptions import (25+ HTTPError,26+ MaxRetryError,27+ SSLError,28+ TimeoutError)29+30+from .poolmanager import PoolManager, ProxyManager, proxy_from_url31+from .response import HTTPResponse32+from .filepost import encode_multipart_formdata33+34+35+# Set default logging handler to avoid "No handler found" warnings.36+import logging37+try:38+ from logging import NullHandler39+except ImportError:40+ class NullHandler(logging.Handler):41+ def emit(self, record):42+ pass43+44+logging.getLogger(__name__).addHandler(NullHandler())45+46+# ... Clean up.47+del logging48+del NullHandleradded:requests/packages/urllib3/_collections.py+120 added
1+# urllib3/_collections.py2+# Copyright 2008-2011 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.php6+7+from collections import MutableMapping, deque8+9+10+__all__ = ['RecentlyUsedContainer']11+12+13+class AccessEntry(object):14+ __slots__ = ('key', 'is_valid')15+16+ def __init__(self, key, is_valid=True):17+ self.key = key18+ self.is_valid = is_valid19+20+21+class RecentlyUsedContainer(MutableMapping):22+ """23+ Provides a dict-like that maintains up to ``maxsize`` keys while throwing24+ away the least-recently-used keys beyond ``maxsize``.25+ """26+27+ # TODO: Make this threadsafe. _prune_invalidated_entries should be the28+ # only real pain-point for this.29+30+ # If len(self.access_log) exceeds self._maxsize * CLEANUP_FACTOR, then we31+ # will attempt to cleanup the invalidated entries in the access_log32+ # datastructure during the next 'get' operation.33+ CLEANUP_FACTOR = 1034+35+ def __init__(self, maxsize=10):36+ self._maxsize = maxsize37+38+ self._container = {}39+40+ # We use a deque to to store our keys ordered by the last access.41+ self.access_log = deque()42+43+ # We look up the access log entry by the key to invalidate it so we can44+ # insert a new authorative entry at the head without having to dig and45+ # find the old entry for removal immediately.46+ self.access_lookup = {}47+48+ # Trigger a heap cleanup when we get past this size49+ self.access_log_limit = maxsize * self.CLEANUP_FACTOR50+51+ def _push_entry(self, key):52+ "Push entry onto our access log, invalidate the old entry if exists."53+ # Invalidate old entry if it exists54+ old_entry = self.access_lookup.get(key)55+ if old_entry:56+ old_entry.is_valid = False57+58+ new_entry = AccessEntry(key)59+60+ self.access_lookup[key] = new_entry61+ self.access_log.appendleft(new_entry)62+63+ def _prune_entries(self, num):64+ "Pop entries from our access log until we popped ``num`` valid ones."65+ while num > 0:66+ p = self.access_log.pop()67+68+ if not p.is_valid:69+ continue # Invalidated entry, skip70+71+ del self._container[p.key]72+ del self.access_lookup[p.key]73+ num -= 174+75+ def _prune_invalidated_entries(self):76+ "Rebuild our access_log without the invalidated entries."77+ self.access_log = deque(e for e in self.access_log if e.is_valid)78+79+ def _get_ordered_access_keys(self):80+ # Used for testing81+ return [e.key for e in self.access_log if e.is_valid]82+83+ def __getitem__(self, key):84+ item = self._container.get(key)85+86+ if not item:87+ return88+89+ # Insert new entry with new high priority, also implicitly invalidates90+ # the old entry.91+ self._push_entry(key)92+93+ if len(self.access_log) > self.access_log_limit:94+ # Heap is getting too big, try to clean up any tailing invalidated95+ # entries.96+ self._prune_invalidated_entries()97+98+ return item99+100+ def __setitem__(self, key, item):101+ # Add item to our container and access log102+ self._container[key] = item103+ self._push_entry(key)104+105+ # Discard invalid and excess entries106+ self._prune_entries(len(self._container) - self._maxsize)107+108+ def __delitem__(self, key):109+ self._invalidate_entry(key)110+ del self._container[key]111+ del self._access_lookup[key]112+113+ def __len__(self):114+ return self._container.__len__()115+116+ def __iter__(self):117+ return self._container.__iter__()118+119+ def __contains__(self, key):120+ return self._container.__contains__(key)added:requests/packages/urllib3/connectionpool.py+525 added
1+# urllib3/connectionpool.py2+# Copyright 2008-2011 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.php6+7+import logging8+import socket9+10+11+from httplib import HTTPConnection, HTTPSConnection, HTTPException12+from Queue import Queue, Empty, Full13+from select import select14+from socket import error as SocketError, timeout as SocketTimeout15+16+17+try:18+ import ssl19+ BaseSSLError = ssl.SSLError20+except ImportError:21+ ssl = None22+ BaseSSLError = None23+24+25+from .request import RequestMethods26+from .response import HTTPResponse27+from .exceptions import (28+ SSLError,29+ MaxRetryError,30+ TimeoutError,31+ HostChangedError,32+ EmptyPoolError,33+)34+35+36+log = logging.getLogger(__name__)37+38+_Default = object()39+40+41+## Connection objects (extension of httplib)42+43+class VerifiedHTTPSConnection(HTTPSConnection):44+ """45+ Based on httplib.HTTPSConnection but wraps the socket with46+ SSL certification.47+ """48+ cert_reqs = None49+ ca_certs = None50+51+ def set_cert(self, key_file=None, cert_file=None,52+ cert_reqs='CERT_NONE', ca_certs=None):53+ ssl_req_scheme = {54+ 'CERT_NONE': ssl.CERT_NONE,55+ 'CERT_OPTIONAL': ssl.CERT_OPTIONAL,56+ 'CERT_REQUIRED': ssl.CERT_REQUIRED57+ }58+59+ self.key_file = key_file60+ self.cert_file = cert_file61+ self.cert_reqs = ssl_req_scheme.get(cert_reqs) or ssl.CERT_NONE62+ self.ca_certs = ca_certs63+64+ def connect(self):65+ # Add certificate verification66+ sock = socket.create_connection((self.host, self.port), self.timeout)67+68+ # Wrap socket using verification with the root certs in69+ # trusted_root_certs70+ self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,71+ cert_reqs=self.cert_reqs,72+ ca_certs=self.ca_certs)73+74+75+## Pool objects76+77+class ConnectionPool(object):78+ """79+ Base class for all connection pools, such as80+ :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.81+ """82+ pass83+84+85+class HTTPConnectionPool(ConnectionPool, RequestMethods):86+ """87+ Thread-safe connection pool for one host.88+89+ :param host:90+ Host used for this HTTP Connection (e.g. "localhost"), passed into91+ :class:`httplib.HTTPConnection`.92+93+ :param port:94+ Port used for this HTTP Connection (None is equivalent to 80), passed95+ into :class:`httplib.HTTPConnection`.96+97+ :param strict:98+ Causes BadStatusLine to be raised if the status line can't be parsed99+ as a valid HTTP/1.0 or 1.1 status line, passed into100+ :class:`httplib.HTTPConnection`.101+102+ :param timeout:103+ Socket timeout for each individual connection, can be a float. None104+ disables timeout.105+106+ :param maxsize:107+ Number of connections to save that can be reused. More than 1 is useful108+ in multithreaded situations. If ``block`` is set to false, more109+ connections will be created but they will not be saved once they've110+ been used.111+112+ :param block:113+ If set to True, no more than ``maxsize`` connections will be used at114+ a time. When no free connections are available, the call will block115+ until a connection has been released. This is a useful side effect for116+ particular multithreaded situations where one does not want to use more117+ than maxsize connections per host to prevent flooding.118+119+ :param headers:120+ Headers to include with all requests, unless other headers are given121+ explicitly.122+ """123+124+ scheme = 'http'125+126+ def __init__(self, host, port=None, strict=False, timeout=None, maxsize=1,127+ block=False, headers=None):128+ self.host = host129+ self.port = port130+ self.strict = strict131+ self.timeout = timeout132+ self.pool = Queue(maxsize)133+ self.block = block134+ self.headers = headers or {}135+136+ # Fill the queue up so that doing get() on it will block properly137+ for _ in xrange(maxsize):138+ self.pool.put(None)139+140+ # These are mostly for testing and debugging purposes.141+ self.num_connections = 0142+ self.num_requests = 0143+144+ def _new_conn(self):145+ """146+ Return a fresh :class:`httplib.HTTPConnection`.147+ """148+ self.num_connections += 1149+ log.info("Starting new HTTP connection (%d): %s" %150+ (self.num_connections, self.host))151+ return HTTPConnection(host=self.host, port=self.port)152+153+ def _get_conn(self, timeout=None):154+ """155+ Get a connection. Will return a pooled connection if one is available.156+157+ If no connections are available and :prop:`.block` is ``False``, then a158+ fresh connection is returned.159+160+ :param timeout:161+ Seconds to wait before giving up and raising162+ :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and163+ :prop:`.block` is ``True``.164+ """165+ conn = None166+ try:167+ conn = self.pool.get(block=self.block, timeout=timeout)168+169+ # If this is a persistent connection, check if it got disconnected170+ if conn and conn.sock and select([conn.sock], [], [], 0.0)[0]:171+ # Either data is buffered (bad), or the connection is dropped.172+ log.info("Resetting dropped connection: %s" % self.host)173+ conn.close()174+175+ except Empty:176+ if self.block:177+ raise EmptyPoolError("Pool reached maximum size and no more "178+ "connections are allowed.")179+ pass # Oh well, we'll create a new connection then180+181+ return conn or self._new_conn()182+183+ def _put_conn(self, conn):184+ """185+ Put a connection back into the pool.186+187+ :param conn:188+ Connection object for the current host and port as returned by189+ :meth:`._new_conn` or :meth:`._get_conn`.190+191+ If the pool is already full, the connection is discarded because we192+ exceeded maxsize. If connections are discarded frequently, then maxsize193+ should be increased.194+ """195+ try:196+ self.pool.put(conn, block=False)197+ except Full:198+ # This should never happen if self.block == True199+ log.warning("HttpConnectionPool is full, discarding connection: %s"200+ % self.host)201+202+ def _make_request(self, conn, method, url, timeout=_Default,203+ **httplib_request_kw):204+ """205+ Perform a request on a given httplib connection object taken from our206+ pool.207+ """208+ self.num_requests += 1209+210+ if timeout is _Default:211+ timeout = self.timeout212+213+ conn.request(method, url, **httplib_request_kw)214+ conn.sock.settimeout(timeout)215+ httplib_response = conn.getresponse()216+217+ log.debug("\"%s %s %s\" %s %s" %218+ (method, url,219+ conn._http_vsn_str, # pylint: disable-msg=W0212220+ httplib_response.status, httplib_response.length))221+222+ return httplib_response223+224+225+ def is_same_host(self, url):226+ """227+ Check if the given ``url`` is a member of the same host as this228+ conncetion pool.229+ """230+ # TODO: Add optional support for socket.gethostbyname checking.231+ return (url.startswith('/') or232+ get_host(url) == (self.scheme, self.host, self.port))233+234+ def urlopen(self, method, url, body=None, headers=None, retries=3,235+ redirect=True, assert_same_host=True, timeout=_Default,236+ pool_timeout=None, release_conn=None, **response_kw):237+ """238+ Get a connection from the pool and perform an HTTP request. This is the239+ lowest level call for making a request, so you'll need to specify all240+ the raw details.241+242+ .. note::243+244+ More commonly, it's appropriate to use a convenience method provided245+ by :class:`.RequestMethods`, such as :meth:`.request`.246+247+ :param method:248+ HTTP request method (such as GET, POST, PUT, etc.)249+250+ :param body:251+ Data to send in the request body (useful for creating252+ POST requests, see HTTPConnectionPool.post_url for253+ more convenience).254+255+ :param headers:256+ Dictionary of custom headers to send, such as User-Agent,257+ If-None-Match, etc. If None, pool headers are used. If provided,258+ these headers completely replace any pool-specific headers.259+260+ :param retries:261+ Number of retries to allow before raising a MaxRetryError exception.262+263+ :param redirect:264+ Automatically handle redirects (status codes 301, 302, 303, 307),265+ each redirect counts as a retry.266+267+ :param assert_same_host:268+ If ``True``, will make sure that the host of the pool requests is269+ consistent else will raise HostChangedError. When False, you can270+ use the pool on an HTTP proxy and request foreign hosts.271+272+ :param timeout:273+ If specified, overrides the default timeout for this one request.274+275+ :param pool_timeout:276+ If set and the pool is set to block=True, then this method will277+ block for ``pool_timeout`` seconds and raise EmptyPoolError if no278+ connection is available within the time period.279+280+ :param release_conn:281+ If False, then the urlopen call will not release the connection282+ back into the pool once a response is received. This is useful if283+ you're not preloading the response's content immediately. You will284+ need to call ``r.release_conn()`` on the response ``r`` to return285+ the connection back into the pool. If None, it takes the value of286+ ``response_kw.get('preload_content', True)``.287+288+ :param \**response_kw:289+ Additional parameters are passed to290+ :meth:`urllib3.response.HTTPResponse.from_httplib`291+ """292+ if headers is None:293+ headers = self.headers294+295+ if retries < 0:296+ raise MaxRetryError("Max retries exceeded for url: %s" % url)297+298+ if release_conn is None:299+ release_conn = response_kw.get('preload_content', True)300+301+ # Check host302+ if assert_same_host and not self.is_same_host(url):303+ host = "%s://%s" % (self.scheme, self.host)304+ if self.port:305+ host = "%s:%d" % (host, self.port)306+307+ raise HostChangedError("Connection pool with host '%s' tried to "308+ "open a foreign host: %s" % (host, url))309+310+ conn = None311+312+ try:313+ # Request a connection from the queue314+ # (Could raise SocketError: Bad file descriptor)315+ conn = self._get_conn(timeout=pool_timeout)316+317+ # Make the request on the httplib connection object318+ httplib_response = self._make_request(conn, method, url,319+ timeout=timeout,320+ body=body, headers=headers)321+322+ # If we're going to release the connection in ``finally:``, then323+ # the request doesn't need to know about the connection. Otherwise324+ # it will also try to release it and we'll have a double-release325+ # mess.326+ response_conn = not release_conn and conn327+328+ # Import httplib's response into our own wrapper object329+ response = HTTPResponse.from_httplib(httplib_response,330+ pool=self,331+ connection=response_conn,332+ **response_kw)333+334+ # else:335+ # The connection will be put back into the pool when336+ # ``response.release_conn()`` is called (implicitly by337+ # ``response.read()``)338+339+ except (SocketTimeout, Empty), e:340+ # Timed out either by socket or queue341+ raise TimeoutError("Request timed out after %f seconds" %342+ self.timeout)343+344+ except (BaseSSLError), e:345+ # SSL certificate error346+ raise SSLError(e)347+348+ except (HTTPException, SocketError), e:349+ # Connection broken, discard. It will be replaced next _get_conn().350+ conn = None351+352+ finally:353+ if conn and release_conn:354+ # Put the connection back to be reused355+ self._put_conn(conn)356+357+ if not conn:358+ log.warn("Retrying (%d attempts remain) after connection "359+ "broken by '%r': %s" % (retries, e, url))360+ return self.urlopen(method, url, body, headers, retries - 1,361+ redirect, assert_same_host) # Try again362+363+ # Handle redirection364+ if (redirect and365+ response.status in [301, 302, 303, 307] and366+ 'location' in response.headers): # Redirect, retry367+ log.info("Redirecting %s -> %s" %368+ (url, response.headers.get('location')))369+ return self.urlopen(method, response.headers.get('location'), body,370+ headers, retries - 1, redirect,371+ assert_same_host)372+373+ return response374+375+376+class HTTPSConnectionPool(HTTPConnectionPool):377+ """378+ Same as :class:`.HTTPConnectionPool`, but HTTPS.379+380+ When Python is compiled with the :mod:`ssl` module, then381+ :class:`.VerifiedHTTPSConnection` is used, which *can* verify certificates,382+ instead of :class:httplib.HTTPSConnection`.383+384+ The ``key_file``, ``cert_file``, ``cert_reqs``, and ``ca_certs`` parameters385+ are only used if :mod:`ssl` is available and are fed into386+ :meth:`ssl.wrap_socket` to upgrade the connection socket into an SSL socket.387+ """388+389+ scheme = 'https'390+391+ def __init__(self, host, port=None,392+ strict=False, timeout=None, maxsize=1,393+ block=False, headers=None,394+ key_file=None, cert_file=None,395+ cert_reqs='CERT_NONE', ca_certs=None):396+397+ super(HTTPSConnectionPool, self).__init__(host, port,398+ strict, timeout, maxsize,399+ block, headers)400+ self.key_file = key_file401+ self.cert_file = cert_file402+ self.cert_reqs = cert_reqs403+ self.ca_certs = ca_certs404+405+ def _new_conn(self):406+ """407+ Return a fresh :class:`httplib.HTTPSConnection`.408+ """409+ self.num_connections += 1410+ log.info("Starting new HTTPS connection (%d): %s"411+ % (self.num_connections, self.host))412+413+ if not ssl:414+ return HTTPSConnection(host=self.host, port=self.port)415+416+ connection = VerifiedHTTPSConnection(host=self.host, port=self.port)417+ connection.set_cert(key_file=self.key_file, cert_file=self.cert_file,418+ cert_reqs=self.cert_reqs, ca_certs=self.ca_certs)419+ return connection420+421+422+## Helpers423+424+def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,425+ basic_auth=None):426+ """427+ Shortcuts for generating request headers.428+429+ :param keep_alive:430+ If ``True``, adds 'connection: keep-alive' header.431+432+ :param accept_encoding:433+ Can be a boolean, list, or string.434+ ``True`` translates to 'gzip,deflate'.435+ List will get joined by comma.436+ String will be used as provided.437+438+ :param user_agent:439+ String representing the user-agent you want, such as440+ "python-urllib3/0.6"441+442+ :param basic_auth:443+ Colon-separated username:password string for 'authorization: basic ...'444+ auth header.445+446+ Example: ::447+448+ >>> make_headers(keep_alive=True, user_agent="Batman/1.0")449+ {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}450+ >>> make_headers(accept_encoding=True)451+ {'accept-encoding': 'gzip,deflate'}452+ """453+ headers = {}454+ if accept_encoding:455+ if isinstance(accept_encoding, str):456+ pass457+ elif isinstance(accept_encoding, list):458+ accept_encoding = ','.join(accept_encoding)459+ else:460+ accept_encoding = 'gzip,deflate'461+ headers['accept-encoding'] = accept_encoding462+463+ if user_agent:464+ headers['user-agent'] = user_agent465+466+ if keep_alive:467+ headers['connection'] = 'keep-alive'468+469+ if basic_auth:470+ headers['authorization'] = 'Basic ' + \471+ basic_auth.encode('base64').strip()472+473+ return headers474+475+476+def get_host(url):477+ """478+ Given a url, return its scheme, host and port (None if it's not there).479+480+ For example: ::481+482+ >>> get_host('http://google.com/mail/')483+ ('http', 'google.com', None)484+ >>> get_host('google.com:80')485+ ('http', 'google.com', 80)486+ """487+ # This code is actually similar to urlparse.urlsplit, but much488+ # simplified for our needs.489+ port = None490+ scheme = 'http'491+ if '//' in url:492+ scheme, url = url.split('://', 1)493+ if '/' in url:494+ url, _path = url.split('/', 1)495+ if ':' in url:496+ url, port = url.split(':', 1)497+ port = int(port)498+ return scheme, url, port499+500+501+def connection_from_url(url, **kw):502+ """503+ Given a url, return an :class:`.ConnectionPool` instance of its host.504+505+ This is a shortcut for not having to parse out the scheme, host, and port506+ of the url before creating an :class:`.ConnectionPool` instance.507+508+ :param url:509+ Absolute URL string that must include the scheme. Port is optional.510+511+ :param \**kw:512+ Passes additional parameters to the constructor of the appropriate513+ :class:`.ConnectionPool`. Useful for specifying things like514+ timeout, maxsize, headers, etc.515+516+ Example: ::517+518+ >>> conn = connection_from_url('http://google.com/')519+ >>> r = conn.request('GET', '/')520+ """521+ scheme, host, port = get_host(url)522+ if scheme == 'https':523+ return HTTPSConnectionPool(host, port=port, **kw)524+ else:525+ return HTTPConnectionPool(host, port=port, **kw)added:requests/packages/urllib3/exceptions.py+35 added
1+# urllib3/exceptions.py2+# Copyright 2008-2011 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.php6+7+## Exceptions8+9+class HTTPError(Exception):10+ "Base exception used by this module."11+ pass12+13+14+class SSLError(Exception):15+ "Raised when SSL certificate fails in an HTTPS connection."16+ pass17+18+19+class MaxRetryError(HTTPError):20+ "Raised when the maximum number of retries is exceeded."21+ pass22+23+24+class TimeoutError(HTTPError):25+ "Raised when a socket timeout occurs."26+ pass27+28+29+class HostChangedError(HTTPError):30+ "Raised when an existing pool gets a request for a foreign host."31+ pass32+33+class EmptyPoolError(HTTPError):34+ "Raised when a pool runs out of connections and no more are allowed."35+ passadded:requests/packages/urllib3/filepost.py+71 added
1+# urllib3/filepost.py2+# Copyright 2008-2011 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.php6+7+import codecs8+import mimetools9+import mimetypes10+11+try:12+ from cStringIO import StringIO13+except ImportError:14+ from StringIO import StringIO # pylint: disable-msg=W040415+16+17+writer = codecs.lookup('utf-8')[3]18+19+20+def get_content_type(filename):21+ return mimetypes.guess_type(filename)[0] or 'application/octet-stream'22+23+24+def encode_multipart_formdata(fields, boundary=None):25+ """26+ Encode a dictionary of ``fields`` using the multipart/form-data mime format.27+28+ :param fields:29+ Dictionary of fields. The key is treated as the field name, and the30+ value as the body of the form-data. If the value is a tuple of two31+ elements, then the first element is treated as the filename of the32+ form-data section.33+34+ :param boundary:35+ If not specified, then a random boundary will be generated using36+ :func:`mimetools.choose_boundary`.37+ """38+ body = StringIO()39+ if boundary is None:40+ boundary = mimetools.choose_boundary()41+42+ for fieldname, value in fields.iteritems():43+ body.write('--%s\r\n' % (boundary))44+45+ if isinstance(value, tuple):46+ filename, data = value47+ writer(body).write('Content-Disposition: form-data; name="%s"; '48+ 'filename="%s"\r\n' % (fieldname, filename))49+ body.write('Content-Type: %s\r\n\r\n' %50+ (get_content_type(filename)))51+ else:52+ data = value53+ writer(body).write('Content-Disposition: form-data; name="%s"\r\n'54+ % (fieldname))55+ body.write('Content-Type: text/plain\r\n\r\n')56+57+ if isinstance(data, int):58+ data = str(data) # Backwards compatibility59+60+ if isinstance(data, unicode):61+ writer(body).write(data)62+ else:63+ body.write(data)64+65+ body.write('\r\n')66+67+ body.write('--%s--\r\n' % (boundary))68+69+ content_type = 'multipart/form-data; boundary=%s' % boundary70+71+ return body.getvalue(), content_typeadded:requests/packages/urllib3/poolmanager.py+128 added
1+# urllib3/poolmanager.py2+# Copyright 2008-2011 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.php6+7+from ._collections import RecentlyUsedContainer8+from .connectionpool import (9+ HTTPConnectionPool, HTTPSConnectionPool,10+ get_host, connection_from_url,11+)12+13+14+__all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']15+16+17+from .request import RequestMethods18+from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool19+20+21+pool_classes_by_scheme = {22+ 'http': HTTPConnectionPool,23+ 'https': HTTPSConnectionPool,24+}25+26+port_by_scheme = {27+ 'http': 80,28+ 'https': 443,29+}30+31+32+class PoolManager(RequestMethods):33+ """34+ Allows for arbitrary requests while transparently keeping track of35+ necessary connection pools for you.36+37+ :param num_pools:38+ Number of connection pools to cache before discarding the least recently39+ used pool.40+41+ :param \**connection_pool_kw:42+ Additional parameters are used to create fresh43+ :class:`urllib3.connectionpool.ConnectionPool` instances.44+45+ Example: ::46+47+ >>> manager = PoolManager()48+ >>> r = manager.urlopen("http://google.com/")49+ >>> r = manager.urlopen("http://google.com/mail")50+ >>> r = manager.urlopen("http://yahoo.com/")51+ >>> len(r.pools)52+ 253+54+ """55+56+ # TODO: Make sure there are no memory leaks here.57+58+ def __init__(self, num_pools=10, **connection_pool_kw):59+ self.connection_pool_kw = connection_pool_kw60+ self.pools = RecentlyUsedContainer(num_pools)61+62+ def connection_from_host(self, host, port=80, scheme='http'):63+ """64+ Get a :class:`ConnectionPool` based on the host, port, and scheme.65+66+ Note that an appropriate ``port`` value is required here to normalize67+ connection pools in our container most effectively.68+ """69+ pool_key = (scheme, host, port)70+71+ # If the scheme, host, or port doesn't match existing open connections,72+ # open a new ConnectionPool.73+ pool = self.pools.get(pool_key)74+ if pool:75+ return pool76+77+ # Make a fresh ConnectionPool of the desired type78+ pool_cls = pool_classes_by_scheme[scheme]79+ pool = pool_cls(host, port, **self.connection_pool_kw)80+81+ self.pools[pool_key] = pool82+83+ return pool84+85+ def connection_from_url(self, url):86+ """87+ Similar to :func:`urllib3.connectionpool.connection_from_url` but88+ doesn't pass any additional parameters to the89+ :class:`urllib3.connectionpool.ConnectionPool` constructor.90+91+ Additional parameters are taken from the :class:`.PoolManager`92+ constructor.93+ """94+ scheme, host, port = get_host(url)95+96+ port = port or port_by_scheme.get(scheme, 80)97+98+ return self.connection_from_host(host, port=port, scheme=scheme)99+100+ def urlopen(self, method, url, **kw):101+ """102+ Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`.103+104+ ``url`` must be absolute, such that an appropriate105+ :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.106+ """107+ conn = self.connection_from_url(url)108+ return conn.urlopen(method, url, assert_same_host=False, **kw)109+110+111+class ProxyManager(object):112+ """113+ Given a ConnectionPool to a proxy, the ProxyManager's ``urlopen`` method114+ will make requests to any url through the defined proxy.115+ """116+117+ def __init__(self, proxy_pool):118+ self.proxy_pool = proxy_pool119+120+ def urlopen(self, method, url, **kw):121+ "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."122+ kw['assert_same_host'] = False123+ return self.proxy_pool.urlopen(method, url, **kw)124+125+126+def proxy_from_url(url, **pool_kw):127+ proxy_pool = connection_from_url(url, **pool_kw)128+ return ProxyManager(proxy_pool)added:requests/packages/urllib3/request.py+145 added
1+# urllib3/request.py2+# Copyright 2008-2011 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.php6+7+8+from urllib import urlencode9+10+from .filepost import encode_multipart_formdata11+12+13+__all__ = ['RequestMethods']14+15+16+class RequestMethods(object):17+ """18+ Convenience mixin for classes who implement a :meth:`urlopen` method, such19+ as :class:`~urllib3.connectionpool.HTTPConnectionPool` and20+ :class:`~urllib3.poolmanager.PoolManager`.21+22+ Provides behavior for making common types of HTTP request methods and23+ decides which type of request field encoding to use.24+25+ Specifically,26+27+ :meth:`.request_encode_url` is for sending requests whose fields are encoded28+ in the URL (such as GET, HEAD, DELETE).29+30+ :meth:`.request_encode_body` is for sending requests whose fields are31+ encoded in the *body* of the request using multipart or www-orm-urlencoded32+ (such as for POST, PUT, PATCH).33+34+ :meth:`.request` is for making any kind of request, it will look up the35+ appropriate encoding format and use one of the above two methods to make36+ the request.37+ """38+39+ _encode_url_methods = set(['DELETE', 'GET', 'HEAD', 'OPTIONS'])40+41+ _encode_body_methods = set(['PATCH', 'POST', 'PUT', 'TRACE'])42+43+ def urlopen(self, method, url, body=None, headers=None,44+ encode_multipart=True, multipart_boundary=None,45+ **kw):46+ raise NotImplemented("Classes extending RequestMethods must implement "47+ "their own ``urlopen`` method.")48+49+ def request(self, method, url, fields=None, headers=None, **urlopen_kw):50+ """51+ Make a request using :meth:`urlopen` with the appropriate encoding of52+ ``fields`` based on the ``method`` used.53+54+ This is a convenience method that requires the least amount of manual55+ effort. It can be used in most situations, while still having the option56+ to drop down to more specific methods when necessary, such as57+ :meth:`request_encode_url`, :meth:`request_encode_body`,58+ or even the lowest level :meth:`urlopen`.59+ """60+ method = method.upper()61+62+ if method in self._encode_url_methods:63+ return self.request_encode_url(method, url, fields=fields,64+ headers=headers,65+ **urlopen_kw)66+ else:67+ return self.request_encode_body(method, url, fields=fields,68+ headers=headers,69+ **urlopen_kw)70+71+ def request_encode_url(self, method, url, fields=None, **urlopen_kw):72+ """73+ Make a request using :meth:`urlopen` with the ``fields`` encoded in74+ the url. This is useful for request methods like GET, HEAD, DELETE, etc.75+ """76+ if fields:77+ url += '?' + urlencode(fields)78+ return self.urlopen(method, url, **urlopen_kw)79+80+ def request_encode_body(self, method, url, fields=None, headers=None,81+ encode_multipart=True, multipart_boundary=None,82+ **urlopen_kw):83+ """84+ Make a request using :meth:`urlopen` with the ``fields`` encoded in85+ the body. This is useful for request methods like POST, PUT, PATCH, etc.86+87+ When ``encode_multipart=True`` (default), then88+ :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the89+ payload with the appropriate content type. Otherwise90+ :meth:`urllib.urlencode` is used with the91+ 'application/x-www-form-urlencoded' content type.92+93+ Multipart encoding must be used when posting files, and it's reasonably94+ safe to use it in other times too. However, it may break request signing,95+ such as with OAuth.96+97+ Supports an optional ``fields`` parameter of key/value strings AND98+ key/filetuple. A filetuple is a (filename, data) tuple. For example: ::99+100+ fields = {101+ 'foo': 'bar',102+ 'fakefile': ('foofile.txt', 'contents of foofile'),103+ 'realfile': ('barfile.txt', open('realfile').read()),104+ 'nonamefile': ('contents of nonamefile field'),105+ }106+107+ When uploading a file, providing a filename (the first parameter of the108+ tuple) is optional but recommended to best mimick behavior of browsers.109+110+ Note that if ``headers`` are supplied, the 'Content-Type' header will be111+ overwritten because it depends on the dynamic random boundary string112+ which is used to compose the body of the request. The random boundary113+ string can be explicitly set with the ``multipart_boundary`` parameter.114+ """115+ if encode_multipart:116+ body, content_type = encode_multipart_formdata(fields or {},117+ boundary=multipart_boundary)118+ else:119+ body, content_type = (urlencode(fields or {}),120+ 'application/x-www-form-urlencoded')121+122+ headers = headers or {}123+ headers.update({'Content-Type': content_type})124+125+ return self.urlopen(method, url, body=body, headers=headers,126+ **urlopen_kw)127+128+ # Deprecated:129+130+ def get_url(self, url, fields=None, **urlopen_kw):131+ """132+ .. deprecated:: 1.0133+ Use :meth:`request` instead.134+ """135+ return self.request_encode_url('GET', url, fields=fields,136+ **urlopen_kw)137+138+ def post_url(self, url, fields=None, headers=None, **urlopen_kw):139+ """140+ .. deprecated:: 1.0141+ Use :meth:`request` instead.142+ """143+ return self.request_encode_body('POST', url, fields=fields,144+ headers=headers,145+ **urlopen_kw)added:requests/packages/urllib3/response.py+181 added
1+# urllib3/response.py2+# Copyright 2008-2011 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.php6+7+import gzip8+import logging9+import zlib10+11+12+try:13+ from cStringIO import StringIO14+except ImportError:15+ from StringIO import StringIO # pylint: disable-msg=W040416+17+18+from .exceptions import HTTPError19+20+21+log = logging.getLogger(__name__)22+23+24+def decode_gzip(data):25+ gzipper = gzip.GzipFile(fileobj=StringIO(data))26+ return gzipper.read()27+28+29+def decode_deflate(data):30+ try:31+ return zlib.decompress(data)32+ except zlib.error:33+ return zlib.decompress(data, -zlib.MAX_WBITS)34+35+36+class HTTPResponse(object):37+ """38+ HTTP Response container.39+40+ Backwards-compatible to httplib's HTTPResponse but the response ``body`` is41+ loaded and decoded on-demand when the ``data`` property is accessed.42+43+ Extra parameters for behaviour not present in httplib.HTTPResponse:44+45+ :param preload_content:46+ If True, the response's body will be preloaded during construction.47+48+ :param decode_content:49+ If True, attempts to decode specific content-encoding's based on headers50+ (like 'gzip' and 'deflate') will be skipped and raw data will be used51+ instead.52+53+ :param original_response:54+ When this HTTPResponse wrapper is generated from an httplib.HTTPResponse55+ object, it's convenient to include the original for debug purposes. It's56+ otherwise unused.57+ """58+59+ CONTENT_DECODERS = {60+ 'gzip': decode_gzip,61+ 'deflate': decode_deflate,62+ }63+64+ def __init__(self, body='', headers=None, status=0, version=0, reason=None,65+ strict=0, preload_content=True, decode_content=True,66+ original_response=None, pool=None, connection=None):67+ self.headers = headers or {}68+ self.status = status69+ self.version = version70+ self.reason = reason71+ self.strict = strict72+73+ self._decode_content = decode_content74+ self._body = None75+ self._fp = None76+ self._original_response = original_response77+78+ self._pool = pool79+ self._connection = connection80+81+ if hasattr(body, 'read'):82+ self._fp = body83+84+ if preload_content:85+ self._body = self.read(decode_content=decode_content)86+87+ def release_conn(self):88+ if not self._pool or not self._connection:89+ return90+91+ self._pool._put_conn(self._connection)92+ self._connection = None93+94+ @property95+ def data(self):96+ # For backwords-compat with earlier urllib3 0.4 and earlier.97+ if self._body:98+ return self._body99+100+ if self._fp:101+ return self.read(decode_content=self._decode_content,102+ cache_content=True)103+104+ def read(self, amt=None, decode_content=True, cache_content=False):105+ """106+ Similar to :meth:`httplib.HTTPResponse.read`, but with two additional107+ parameters: ``decode_content`` and ``cache_content``.108+109+ :param amt:110+ How much of the content to read. If specified, decoding and caching111+ is skipped because we can't decode partial content nor does it make112+ sense to cache partial content as the full response.113+114+ :param decode_content:115+ If True, will attempt to decode the body based on the116+ 'content-encoding' header. (Overridden if ``amt`` is set.)117+118+ :param cache_content:119+ If True, will save the returned data such that the same result is120+ returned despite of the state of the underlying file object. This121+ is useful if you want the ``.data`` property to continue working122+ after having ``.read()`` the file object. (Overridden if ``amt`` is123+ set.)124+ """125+ content_encoding = self.headers.get('content-encoding')126+ decoder = self.CONTENT_DECODERS.get(content_encoding)127+128+ data = self._fp and self._fp.read(amt)129+130+ try:131+132+ if amt:133+ return data134+135+ if not decode_content or not decoder:136+ if cache_content:137+ self._body = data138+139+ return data140+141+ try:142+ data = decoder(data)143+ except IOError:144+ raise HTTPError("Received response with content-encoding: %s, but "145+ "failed to decode it." % content_encoding)146+147+ if cache_content:148+ self._body = data149+150+ return data151+152+ finally:153+154+ if self._original_response and self._original_response.isclosed():155+ self.release_conn()156+157+ @staticmethod158+ def from_httplib(r, **response_kw):159+ """160+ Given an :class:`httplib.HTTPResponse` instance ``r``, return a161+ corresponding :class:`urllib3.response.HTTPResponse` object.162+163+ Remaining parameters are passed to the HTTPResponse constructor, along164+ with ``original_response=r``.165+ """166+167+ return HTTPResponse(body=r,168+ headers=dict(r.getheaders()),169+ status=r.status,170+ version=r.version,171+ reason=r.reason,172+ strict=r.strict,173+ original_response=r,174+ **response_kw)175+176+ # Backwards-compatibility methods for httplib.HTTPResponse177+ def getheaders(self):178+ return self.headers179+180+ def getheader(self, name, default=None):181+ return self.headers.get(name, default)