Skip to content
Myr

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

10 files+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.php67"""8NTLM authenticating pool, contributed by erikcederstran910Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=1011"""1213import httplib14from logging import getLogger15from ntlm import ntlm1617from urllib3 import HTTPSConnectionPool181920log = getLogger(__name__)212223class NTLMConnectionPool(HTTPSConnectionPool):24 """25 Implements an NTLM authentication version of an urllib3 connection pool26 """2728 scheme = 'https'2930 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 = pw4344 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))5051 headers = {}52 headers['Connection'] = 'Keep-Alive'53 req_header = 'Authorization'54 resp_header = 'www-authenticate'5556 conn = httplib.HTTPSConnection(host=self.host, port=self.port)5758 # 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))6869 # 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 = None7273 # 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]))8283 # 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))104105 res.fp = None106 log.debug('Connection established')107 return conn108109 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.php67"""8urllib3 - Thread-safe connection pooling and re-using.9"""1011__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'12__license__ = 'MIT'13__version__ = '1.0.1'141516from .connectionpool import (17 HTTPConnectionPool,18 HTTPSConnectionPool,19 connection_from_url,20 get_host,21 make_headers)222324from .exceptions import (25 HTTPError,26 MaxRetryError,27 SSLError,28 TimeoutError)2930from .poolmanager import PoolManager, ProxyManager, proxy_from_url31from .response import HTTPResponse32from .filepost import encode_multipart_formdata333435# Set default logging handler to avoid "No handler found" warnings.36import logging37try:38 from logging import NullHandler39except ImportError:40 class NullHandler(logging.Handler):41 def emit(self, record):42 pass4344logging.getLogger(__name__).addHandler(NullHandler())4546# ... Clean up.47del logging48del NullHandler
added: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.php67from collections import MutableMapping, deque8910__all__ = ['RecentlyUsedContainer']111213class AccessEntry(object):14 __slots__ = ('key', 'is_valid')1516 def __init__(self, key, is_valid=True):17 self.key = key18 self.is_valid = is_valid192021class 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 """2627 # TODO: Make this threadsafe. _prune_invalidated_entries should be the28 # only real pain-point for this.2930 # 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 = 103435 def __init__(self, maxsize=10):36 self._maxsize = maxsize3738 self._container = {}3940 # We use a deque to to store our keys ordered by the last access.41 self.access_log = deque()4243 # 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 = {}4748 # Trigger a heap cleanup when we get past this size49 self.access_log_limit = maxsize * self.CLEANUP_FACTOR5051 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 = False5758 new_entry = AccessEntry(key)5960 self.access_lookup[key] = new_entry61 self.access_log.appendleft(new_entry)6263 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()6768 if not p.is_valid:69 continue # Invalidated entry, skip7071 del self._container[p.key]72 del self.access_lookup[p.key]73 num -= 17475 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)7879 def _get_ordered_access_keys(self):80 # Used for testing81 return [e.key for e in self.access_log if e.is_valid]8283 def __getitem__(self, key):84 item = self._container.get(key)8586 if not item:87 return8889 # Insert new entry with new high priority, also implicitly invalidates90 # the old entry.91 self._push_entry(key)9293 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()9798 return item99100 def __setitem__(self, key, item):101 # Add item to our container and access log102 self._container[key] = item103 self._push_entry(key)104105 # Discard invalid and excess entries106 self._prune_entries(len(self._container) - self._maxsize)107108 def __delitem__(self, key):109 self._invalidate_entry(key)110 del self._container[key]111 del self._access_lookup[key]112113 def __len__(self):114 return self._container.__len__()115116 def __iter__(self):117 return self._container.__iter__()118119 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.php67import logging8import socket91011from httplib import HTTPConnection, HTTPSConnection, HTTPException12from Queue import Queue, Empty, Full13from select import select14from socket import error as SocketError, timeout as SocketTimeout151617try:18 import ssl19 BaseSSLError = ssl.SSLError20except ImportError:21 ssl = None22 BaseSSLError = None232425from .request import RequestMethods26from .response import HTTPResponse27from .exceptions import (28 SSLError,29 MaxRetryError,30 TimeoutError,31 HostChangedError,32 EmptyPoolError,33)343536log = logging.getLogger(__name__)3738_Default = object()394041## Connection objects (extension of httplib)4243class VerifiedHTTPSConnection(HTTPSConnection):44 """45 Based on httplib.HTTPSConnection but wraps the socket with46 SSL certification.47 """48 cert_reqs = None49 ca_certs = None5051 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 }5859 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_certs6364 def connect(self):65 # Add certificate verification66 sock = socket.create_connection((self.host, self.port), self.timeout)6768 # 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)737475## Pool objects7677class ConnectionPool(object):78 """79 Base class for all connection pools, such as80 :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.81 """82 pass838485class HTTPConnectionPool(ConnectionPool, RequestMethods):86 """87 Thread-safe connection pool for one host.8889 :param host:90 Host used for this HTTP Connection (e.g. "localhost"), passed into91 :class:`httplib.HTTPConnection`.9293 :param port:94 Port used for this HTTP Connection (None is equivalent to 80), passed95 into :class:`httplib.HTTPConnection`.9697 :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`.101102 :param timeout:103 Socket timeout for each individual connection, can be a float. None104 disables timeout.105106 :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.111112 :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.118119 :param headers:120 Headers to include with all requests, unless other headers are given121 explicitly.122 """123124 scheme = 'http'125126 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 {}135136 # Fill the queue up so that doing get() on it will block properly137 for _ in xrange(maxsize):138 self.pool.put(None)139140 # These are mostly for testing and debugging purposes.141 self.num_connections = 0142 self.num_requests = 0143144 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)152153 def _get_conn(self, timeout=None):154 """155 Get a connection. Will return a pooled connection if one is available.156157 If no connections are available and :prop:`.block` is ``False``, then a158 fresh connection is returned.159160 :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)168169 # 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()174175 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 then180181 return conn or self._new_conn()182183 def _put_conn(self, conn):184 """185 Put a connection back into the pool.186187 :param conn:188 Connection object for the current host and port as returned by189 :meth:`._new_conn` or :meth:`._get_conn`.190191 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)201202 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 += 1209210 if timeout is _Default:211 timeout = self.timeout212213 conn.request(method, url, **httplib_request_kw)214 conn.sock.settimeout(timeout)215 httplib_response = conn.getresponse()216217 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))221222 return httplib_response223224225 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))233234 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.241242 .. note::243244 More commonly, it's appropriate to use a convenience method provided245 by :class:`.RequestMethods`, such as :meth:`.request`.246247 :param method:248 HTTP request method (such as GET, POST, PUT, etc.)249250 :param body:251 Data to send in the request body (useful for creating252 POST requests, see HTTPConnectionPool.post_url for253 more convenience).254255 :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.259260 :param retries:261 Number of retries to allow before raising a MaxRetryError exception.262263 :param redirect:264 Automatically handle redirects (status codes 301, 302, 303, 307),265 each redirect counts as a retry.266267 :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.271272 :param timeout:273 If specified, overrides the default timeout for this one request.274275 :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.279280 :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)``.287288 :param \**response_kw:289 Additional parameters are passed to290 :meth:`urllib3.response.HTTPResponse.from_httplib`291 """292 if headers is None:293 headers = self.headers294295 if retries < 0:296 raise MaxRetryError("Max retries exceeded for url: %s" % url)297298 if release_conn is None:299 release_conn = response_kw.get('preload_content', True)300301 # 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)306307 raise HostChangedError("Connection pool with host '%s' tried to "308 "open a foreign host: %s" % (host, url))309310 conn = None311312 try:313 # Request a connection from the queue314 # (Could raise SocketError: Bad file descriptor)315 conn = self._get_conn(timeout=pool_timeout)316317 # Make the request on the httplib connection object318 httplib_response = self._make_request(conn, method, url,319 timeout=timeout,320 body=body, headers=headers)321322 # 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 conn327328 # 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)333334 # else:335 # The connection will be put back into the pool when336 # ``response.release_conn()`` is called (implicitly by337 # ``response.read()``)338339 except (SocketTimeout, Empty), e:340 # Timed out either by socket or queue341 raise TimeoutError("Request timed out after %f seconds" %342 self.timeout)343344 except (BaseSSLError), e:345 # SSL certificate error346 raise SSLError(e)347348 except (HTTPException, SocketError), e:349 # Connection broken, discard. It will be replaced next _get_conn().350 conn = None351352 finally:353 if conn and release_conn:354 # Put the connection back to be reused355 self._put_conn(conn)356357 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 again362363 # 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)372373 return response374375376class HTTPSConnectionPool(HTTPConnectionPool):377 """378 Same as :class:`.HTTPConnectionPool`, but HTTPS.379380 When Python is compiled with the :mod:`ssl` module, then381 :class:`.VerifiedHTTPSConnection` is used, which *can* verify certificates,382 instead of :class:httplib.HTTPSConnection`.383384 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 """388389 scheme = 'https'390391 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):396397 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_certs404405 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))412413 if not ssl:414 return HTTPSConnection(host=self.host, port=self.port)415416 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 connection420421422## Helpers423424def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,425 basic_auth=None):426 """427 Shortcuts for generating request headers.428429 :param keep_alive:430 If ``True``, adds 'connection: keep-alive' header.431432 :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.437438 :param user_agent:439 String representing the user-agent you want, such as440 "python-urllib3/0.6"441442 :param basic_auth:443 Colon-separated username:password string for 'authorization: basic ...'444 auth header.445446 Example: ::447448 >>> 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_encoding462463 if user_agent:464 headers['user-agent'] = user_agent465466 if keep_alive:467 headers['connection'] = 'keep-alive'468469 if basic_auth:470 headers['authorization'] = 'Basic ' + \471 basic_auth.encode('base64').strip()472473 return headers474475476def get_host(url):477 """478 Given a url, return its scheme, host and port (None if it's not there).479480 For example: ::481482 >>> 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, port499500501def connection_from_url(url, **kw):502 """503 Given a url, return an :class:`.ConnectionPool` instance of its host.504505 This is a shortcut for not having to parse out the scheme, host, and port506 of the url before creating an :class:`.ConnectionPool` instance.507508 :param url:509 Absolute URL string that must include the scheme. Port is optional.510511 :param \**kw:512 Passes additional parameters to the constructor of the appropriate513 :class:`.ConnectionPool`. Useful for specifying things like514 timeout, maxsize, headers, etc.515516 Example: ::517518 >>> 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.php67## Exceptions89class HTTPError(Exception):10 "Base exception used by this module."11 pass121314class SSLError(Exception):15 "Raised when SSL certificate fails in an HTTPS connection."16 pass171819class MaxRetryError(HTTPError):20 "Raised when the maximum number of retries is exceeded."21 pass222324class TimeoutError(HTTPError):25 "Raised when a socket timeout occurs."26 pass272829class HostChangedError(HTTPError):30 "Raised when an existing pool gets a request for a foreign host."31 pass3233class EmptyPoolError(HTTPError):34 "Raised when a pool runs out of connections and no more are allowed."35 pass
added: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.php67import codecs8import mimetools9import mimetypes1011try:12 from cStringIO import StringIO13except ImportError:14 from StringIO import StringIO # pylint: disable-msg=W0404151617writer = codecs.lookup('utf-8')[3]181920def get_content_type(filename):21 return mimetypes.guess_type(filename)[0] or 'application/octet-stream'222324def encode_multipart_formdata(fields, boundary=None):25 """26 Encode a dictionary of ``fields`` using the multipart/form-data mime format.2728 :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.3334 :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()4142 for fieldname, value in fields.iteritems():43 body.write('--%s\r\n' % (boundary))4445 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')5657 if isinstance(data, int):58 data = str(data) # Backwards compatibility5960 if isinstance(data, unicode):61 writer(body).write(data)62 else:63 body.write(data)6465 body.write('\r\n')6667 body.write('--%s--\r\n' % (boundary))6869 content_type = 'multipart/form-data; boundary=%s' % boundary7071 return body.getvalue(), content_type
added: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.php67from ._collections import RecentlyUsedContainer8from .connectionpool import (9 HTTPConnectionPool, HTTPSConnectionPool,10 get_host, connection_from_url,11)121314__all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']151617from .request import RequestMethods18from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool192021pool_classes_by_scheme = {22 'http': HTTPConnectionPool,23 'https': HTTPSConnectionPool,24}2526port_by_scheme = {27 'http': 80,28 'https': 443,29}303132class PoolManager(RequestMethods):33 """34 Allows for arbitrary requests while transparently keeping track of35 necessary connection pools for you.3637 :param num_pools:38 Number of connection pools to cache before discarding the least recently39 used pool.4041 :param \**connection_pool_kw:42 Additional parameters are used to create fresh43 :class:`urllib3.connectionpool.ConnectionPool` instances.4445 Example: ::4647 >>> 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 25354 """5556 # TODO: Make sure there are no memory leaks here.5758 def __init__(self, num_pools=10, **connection_pool_kw):59 self.connection_pool_kw = connection_pool_kw60 self.pools = RecentlyUsedContainer(num_pools)6162 def connection_from_host(self, host, port=80, scheme='http'):63 """64 Get a :class:`ConnectionPool` based on the host, port, and scheme.6566 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)7071 # 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 pool7677 # 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)8081 self.pools[pool_key] = pool8283 return pool8485 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.9091 Additional parameters are taken from the :class:`.PoolManager`92 constructor.93 """94 scheme, host, port = get_host(url)9596 port = port or port_by_scheme.get(scheme, 80)9798 return self.connection_from_host(host, port=port, scheme=scheme)99100 def urlopen(self, method, url, **kw):101 """102 Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`.103104 ``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)109110111class 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 """116117 def __init__(self, proxy_pool):118 self.proxy_pool = proxy_pool119120 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)124125126def 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.php678from urllib import urlencode910from .filepost import encode_multipart_formdata111213__all__ = ['RequestMethods']141516class 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`.2122 Provides behavior for making common types of HTTP request methods and23 decides which type of request field encoding to use.2425 Specifically,2627 :meth:`.request_encode_url` is for sending requests whose fields are encoded28 in the URL (such as GET, HEAD, DELETE).2930 :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).3334 :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 """3839 _encode_url_methods = set(['DELETE', 'GET', 'HEAD', 'OPTIONS'])4041 _encode_body_methods = set(['PATCH', 'POST', 'PUT', 'TRACE'])4243 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.")4849 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.5354 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()6162 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)7071 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)7980 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.8687 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.9293 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.9697 Supports an optional ``fields`` parameter of key/value strings AND98 key/filetuple. A filetuple is a (filename, data) tuple. For example: ::99100 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 }106107 When uploading a file, providing a filename (the first parameter of the108 tuple) is optional but recommended to best mimick behavior of browsers.109110 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')121122 headers = headers or {}123 headers.update({'Content-Type': content_type})124125 return self.urlopen(method, url, body=body, headers=headers,126 **urlopen_kw)127128 # Deprecated:129130 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)137138 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.php67import gzip8import logging9import zlib101112try:13 from cStringIO import StringIO14except ImportError:15 from StringIO import StringIO # pylint: disable-msg=W0404161718from .exceptions import HTTPError192021log = logging.getLogger(__name__)222324def decode_gzip(data):25 gzipper = gzip.GzipFile(fileobj=StringIO(data))26 return gzipper.read()272829def decode_deflate(data):30 try:31 return zlib.decompress(data)32 except zlib.error:33 return zlib.decompress(data, -zlib.MAX_WBITS)343536class HTTPResponse(object):37 """38 HTTP Response container.3940 Backwards-compatible to httplib's HTTPResponse but the response ``body`` is41 loaded and decoded on-demand when the ``data`` property is accessed.4243 Extra parameters for behaviour not present in httplib.HTTPResponse:4445 :param preload_content:46 If True, the response's body will be preloaded during construction.4748 :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.5253 :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 """5859 CONTENT_DECODERS = {60 'gzip': decode_gzip,61 'deflate': decode_deflate,62 }6364 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 = strict7273 self._decode_content = decode_content74 self._body = None75 self._fp = None76 self._original_response = original_response7778 self._pool = pool79 self._connection = connection8081 if hasattr(body, 'read'):82 self._fp = body8384 if preload_content:85 self._body = self.read(decode_content=decode_content)8687 def release_conn(self):88 if not self._pool or not self._connection:89 return9091 self._pool._put_conn(self._connection)92 self._connection = None9394 @property95 def data(self):96 # For backwords-compat with earlier urllib3 0.4 and earlier.97 if self._body:98 return self._body99100 if self._fp:101 return self.read(decode_content=self._decode_content,102 cache_content=True)103104 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``.108109 :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.113114 :param decode_content:115 If True, will attempt to decode the body based on the116 'content-encoding' header. (Overridden if ``amt`` is set.)117118 :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)127128 data = self._fp and self._fp.read(amt)129130 try:131132 if amt:133 return data134135 if not decode_content or not decoder:136 if cache_content:137 self._body = data138139 return data140141 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)146147 if cache_content:148 self._body = data149150 return data151152 finally:153154 if self._original_response and self._original_response.isclosed():155 self.release_conn()156157 @staticmethod158 def from_httplib(r, **response_kw):159 """160 Given an :class:`httplib.HTTPResponse` instance ``r``, return a161 corresponding :class:`urllib3.response.HTTPResponse` object.162163 Remaining parameters are passed to the HTTPResponse constructor, along164 with ``original_response=r``.165 """166167 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)175176 # Backwards-compatibility methods for httplib.HTTPResponse177 def getheaders(self):178 return self.headers179180 def getheader(self, name, default=None):181 return self.headers.get(name, default)