further
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 786dfdd · Browse files · 8 files·+518 added−435 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+518 added−435 removed
- other:+518 added−435 removed
Provenance
- Commit
2109afc- Tree
a572540- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
786dfdd
8 files changed+518 added−435 removed
added:requests/packages/urllib3/packages/mimetools_choose_boundary/__init__.py+47 added
1+"""The function mimetools.choose_boundary() from Python 2.7, which seems to2+have disappeared in Python 3 (although email.generator._make_boundary() might3+work as a replacement?).4+5+Tweaked to use lock from threading rather than thread.6+"""7+import os8+from threading import Lock9+_counter_lock = Lock()10+11+_counter = 012+def _get_next_counter():13+ global _counter14+ with _counter_lock:15+ _counter += 116+ return _counter17+18+_prefix = None19+20+def choose_boundary():21+ """Return a string usable as a multipart boundary.22+23+ The string chosen is unique within a single program run, and24+ incorporates the user id (if available), process id (if available),25+ and current time. So it's very unlikely the returned string appears26+ in message text, but there's no guarantee.27+28+ The boundary contains dots so you have to quote it in the header."""29+30+ global _prefix31+ import time32+ if _prefix is None:33+ import socket34+ try:35+ hostid = socket.gethostbyname(socket.gethostname())36+ except socket.gaierror:37+ hostid = '127.0.0.1'38+ try:39+ uid = repr(os.getuid())40+ except AttributeError:41+ uid = '1'42+ try:43+ pid = repr(os.getpid())44+ except AttributeError:45+ pid = '1'46+ _prefix = hostid + '.' + uid + '.' + pid47+ return "%s.%.3f.%d" % (_prefix, time.time(), _get_next_counter())added:requests/packages/urllib3/packages/six.py+372 added
1+"""Utilities for writing code that runs on Python 2 and 3"""2+3+#Copyright (c) 2010-2011 Benjamin Peterson4+5+#Permission is hereby granted, free of charge, to any person obtaining a copy of6+#this software and associated documentation files (the "Software"), to deal in7+#the Software without restriction, including without limitation the rights to8+#use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of9+#the Software, and to permit persons to whom the Software is furnished to do so,10+#subject to the following conditions:11+12+#The above copyright notice and this permission notice shall be included in all13+#copies or substantial portions of the Software.14+15+#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR16+#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS17+#FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR18+#COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER19+#IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN20+#CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.21+22+import operator23+import sys24+import types25+26+__author__ = "Benjamin Peterson <benjamin@python.org>"27+__version__ = "1.1.0"28+29+30+# True if we are running on Python 3.31+PY3 = sys.version_info[0] == 332+33+if PY3:34+ string_types = str,35+ integer_types = int,36+ class_types = type,37+ text_type = str38+ binary_type = bytes39+40+ MAXSIZE = sys.maxsize41+else:42+ string_types = basestring,43+ integer_types = (int, long)44+ class_types = (type, types.ClassType)45+ text_type = unicode46+ binary_type = str47+48+ # It's possible to have sizeof(long) != sizeof(Py_ssize_t).49+ class X(object):50+ def __len__(self):51+ return 1 << 3152+ try:53+ len(X())54+ except OverflowError:55+ # 32-bit56+ MAXSIZE = int((1 << 31) - 1)57+ else:58+ # 64-bit59+ MAXSIZE = int((1 << 63) - 1)60+ del X61+62+63+def _add_doc(func, doc):64+ """Add documentation to a function."""65+ func.__doc__ = doc66+67+68+def _import_module(name):69+ """Import module, returning the module after the last dot."""70+ __import__(name)71+ return sys.modules[name]72+73+74+class _LazyDescr(object):75+76+ def __init__(self, name):77+ self.name = name78+79+ def __get__(self, obj, tp):80+ result = self._resolve()81+ setattr(obj, self.name, result)82+ # This is a bit ugly, but it avoids running this again.83+ delattr(tp, self.name)84+ return result85+86+87+class MovedModule(_LazyDescr):88+89+ def __init__(self, name, old, new=None):90+ super(MovedModule, self).__init__(name)91+ if PY3:92+ if new is None:93+ new = name94+ self.mod = new95+ else:96+ self.mod = old97+98+ def _resolve(self):99+ return _import_module(self.mod)100+101+102+class MovedAttribute(_LazyDescr):103+104+ def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):105+ super(MovedAttribute, self).__init__(name)106+ if PY3:107+ if new_mod is None:108+ new_mod = name109+ self.mod = new_mod110+ if new_attr is None:111+ if old_attr is None:112+ new_attr = name113+ else:114+ new_attr = old_attr115+ self.attr = new_attr116+ else:117+ self.mod = old_mod118+ if old_attr is None:119+ old_attr = name120+ self.attr = old_attr121+122+ def _resolve(self):123+ module = _import_module(self.mod)124+ return getattr(module, self.attr)125+126+127+128+class _MovedItems(types.ModuleType):129+ """Lazy loading of moved objects"""130+131+132+_moved_attributes = [133+ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),134+ MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),135+ MovedAttribute("map", "itertools", "builtins", "imap", "map"),136+ MovedAttribute("reload_module", "__builtin__", "imp", "reload"),137+ MovedAttribute("reduce", "__builtin__", "functools"),138+ MovedAttribute("StringIO", "StringIO", "io"),139+ MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),140+ MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),141+142+ MovedModule("builtins", "__builtin__"),143+ MovedModule("configparser", "ConfigParser"),144+ MovedModule("copyreg", "copy_reg"),145+ MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),146+ MovedModule("http_cookies", "Cookie", "http.cookies"),147+ MovedModule("html_entities", "htmlentitydefs", "html.entities"),148+ MovedModule("html_parser", "HTMLParser", "html.parser"),149+ MovedModule("http_client", "httplib", "http.client"),150+ MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),151+ MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),152+ MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),153+ MovedModule("cPickle", "cPickle", "pickle"),154+ MovedModule("queue", "Queue"),155+ MovedModule("reprlib", "repr"),156+ MovedModule("socketserver", "SocketServer"),157+ MovedModule("tkinter", "Tkinter"),158+ MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),159+ MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),160+ MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),161+ MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),162+ MovedModule("tkinter_tix", "Tix", "tkinter.tix"),163+ MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),164+ MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),165+ MovedModule("tkinter_colorchooser", "tkColorChooser",166+ "tkinter.colorchooser"),167+ MovedModule("tkinter_commondialog", "tkCommonDialog",168+ "tkinter.commondialog"),169+ MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),170+ MovedModule("tkinter_font", "tkFont", "tkinter.font"),171+ MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),172+ MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",173+ "tkinter.simpledialog"),174+ MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),175+ MovedModule("winreg", "_winreg"),176+]177+for attr in _moved_attributes:178+ setattr(_MovedItems, attr.name, attr)179+del attr180+181+moves = sys.modules["six.moves"] = _MovedItems("moves")182+183+184+def add_move(move):185+ """Add an item to six.moves."""186+ setattr(_MovedItems, move.name, move)187+188+189+def remove_move(name):190+ """Remove item from six.moves."""191+ try:192+ delattr(_MovedItems, name)193+ except AttributeError:194+ try:195+ del moves.__dict__[name]196+ except KeyError:197+ raise AttributeError("no such move, %r" % (name,))198+199+200+if PY3:201+ _meth_func = "__func__"202+ _meth_self = "__self__"203+204+ _func_code = "__code__"205+ _func_defaults = "__defaults__"206+207+ _iterkeys = "keys"208+ _itervalues = "values"209+ _iteritems = "items"210+else:211+ _meth_func = "im_func"212+ _meth_self = "im_self"213+214+ _func_code = "func_code"215+ _func_defaults = "func_defaults"216+217+ _iterkeys = "iterkeys"218+ _itervalues = "itervalues"219+ _iteritems = "iteritems"220+221+222+if PY3:223+ def get_unbound_function(unbound):224+ return unbound225+226+227+ advance_iterator = next228+229+ def callable(obj):230+ return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)231+else:232+ def get_unbound_function(unbound):233+ return unbound.im_func234+235+236+ def advance_iterator(it):237+ return it.next()238+239+ callable = callable240+_add_doc(get_unbound_function,241+ """Get the function out of a possibly unbound function""")242+243+244+get_method_function = operator.attrgetter(_meth_func)245+get_method_self = operator.attrgetter(_meth_self)246+get_function_code = operator.attrgetter(_func_code)247+get_function_defaults = operator.attrgetter(_func_defaults)248+249+250+def iterkeys(d):251+ """Return an iterator over the keys of a dictionary."""252+ return getattr(d, _iterkeys)()253+254+def itervalues(d):255+ """Return an iterator over the values of a dictionary."""256+ return getattr(d, _itervalues)()257+258+def iteritems(d):259+ """Return an iterator over the (key, value) pairs of a dictionary."""260+ return getattr(d, _iteritems)()261+262+263+if PY3:264+ def b(s):265+ return s.encode("latin-1")266+ def u(s):267+ return s268+ if sys.version_info[1] <= 1:269+ def int2byte(i):270+ return bytes((i,))271+ else:272+ # This is about 2x faster than the implementation above on 3.2+273+ int2byte = operator.methodcaller("to_bytes", 1, "big")274+ import io275+ StringIO = io.StringIO276+ BytesIO = io.BytesIO277+else:278+ def b(s):279+ return s280+ def u(s):281+ return unicode(s, "unicode_escape")282+ int2byte = chr283+ import StringIO284+ StringIO = BytesIO = StringIO.StringIO285+_add_doc(b, """Byte literal""")286+_add_doc(u, """Text literal""")287+288+289+if PY3:290+ import builtins291+ exec_ = getattr(builtins, "exec")292+293+294+ def reraise(tp, value, tb=None):295+ if value.__traceback__ is not tb:296+ raise value.with_traceback(tb)297+ raise value298+299+300+ print_ = getattr(builtins, "print")301+ del builtins302+303+else:304+ def exec_(code, globs=None, locs=None):305+ """Execute code in a namespace."""306+ if globs is None:307+ frame = sys._getframe(1)308+ globs = frame.f_globals309+ if locs is None:310+ locs = frame.f_locals311+ del frame312+ elif locs is None:313+ locs = globs314+ exec("""exec code in globs, locs""")315+316+317+ exec_("""def reraise(tp, value, tb=None):318+ raise tp, value, tb319+""")320+321+322+ def print_(*args, **kwargs):323+ """The new-style print function."""324+ fp = kwargs.pop("file", sys.stdout)325+ if fp is None:326+ return327+ def write(data):328+ if not isinstance(data, basestring):329+ data = str(data)330+ fp.write(data)331+ want_unicode = False332+ sep = kwargs.pop("sep", None)333+ if sep is not None:334+ if isinstance(sep, unicode):335+ want_unicode = True336+ elif not isinstance(sep, str):337+ raise TypeError("sep must be None or a string")338+ end = kwargs.pop("end", None)339+ if end is not None:340+ if isinstance(end, unicode):341+ want_unicode = True342+ elif not isinstance(end, str):343+ raise TypeError("end must be None or a string")344+ if kwargs:345+ raise TypeError("invalid keyword arguments to print()")346+ if not want_unicode:347+ for arg in args:348+ if isinstance(arg, unicode):349+ want_unicode = True350+ break351+ if want_unicode:352+ newline = unicode("\n")353+ space = unicode(" ")354+ else:355+ newline = "\n"356+ space = " "357+ if sep is None:358+ sep = space359+ if end is None:360+ end = newline361+ for i, arg in enumerate(args):362+ if i:363+ write(sep)364+ write(arg)365+ write(end)366+367+_add_doc(reraise, """Reraise an exception.""")368+369+370+def with_metaclass(meta, base=object):371+ """Create a base class with a metaclass."""372+ return meta("NewBase", (base,), {})modified:requests/packages/urllib3/connectionpool.py+56 added-20 removed
5 unmodified lines6 7 import logging8 import socket9 10+from select import poll, POLLIN11+from socket import error as SocketError, timeout as SocketTimeout12+13+14 try: # Python 315 from http.client import HTTPConnection, HTTPSConnection, HTTPException16+ from http.client import HTTP_PORT, HTTPS_PORT17 except ImportError:18 from httplib import HTTPConnection, HTTPSConnection, HTTPException19+ from httplib import HTTP_PORT, HTTPS_PORT20 21 try: # Python 322 from queue import Queue, Empty, Full23 except ImportError:24 from Queue import Queue, Empty, Full19- 20-from select import select21-from socket import error as SocketError, timeout as SocketTimeout25 23-from .packages.ssl_match_hostname import match_hostname, CertificateError24-25-try:26+try: # Compiled with SSL?27 import ssl28 BaseSSLError = ssl.SSLError29 except ImportError:30 ssl = None1 unmodified line32 33 34 from .request import RequestMethods35 from .response import HTTPResponse35-from .exceptions import (36- SSLError,36+from .exceptions import (SSLError,37 MaxRetryError,38 TimeoutError,39 HostChangedError,40 EmptyPoolError,41 )42 43-from . import six43+from urllib3.packages.ssl_match_hostname import match_hostname, CertificateError44+from urllib3.packages import six45+46 xrange = six.moves.xrange47 46-48 log = logging.getLogger(__name__)49 50 _Default = object()51 52+port_by_scheme = {53+ 'http': HTTP_PORT,54+ 'https': HTTPS_PORT,55+}56 57 ## Connection objects (extension of httplib)58 59 class VerifiedHTTPSConnection(HTTPSConnection):35 unmodified lines95 """96 Base class for all connection pools, such as97 :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.98 """94- pass99 100+ scheme = None101 102+ def __init__(self, host, port=None):103+ self.host = host104+ self.port = port105+106+ def __str__(self):107+ return '%s(host=%r, port=%r)' % (type(self).__name__,108+ self.host, self.port)109+110+111 class HTTPConnectionPool(ConnectionPool, RequestMethods):112 """113 Thread-safe connection pool for one host.114 77 unmodified lines192 try:193 conn = self.pool.get(block=self.block, timeout=timeout)194 195 # If this is a persistent connection, check if it got disconnected182- if conn and conn.sock and select([conn.sock], [], [], 0.0)[0]:183- # Either data is buffered (bad), or the connection is dropped.196+ if conn and conn.sock and is_connection_dropped(conn):197 log.info("Resetting dropped connection: %s" % self.host)198 conn.close()199 200 except Empty:201 if self.block:189- raise EmptyPoolError("Pool reached maximum size and no more "202+ raise EmptyPoolError(self,203+ "Pool reached maximum size and no more "204 "connections are allowed.")205 pass # Oh well, we'll create a new connection then206 207 return conn or self._new_conn()44 unmodified lines252 253 def is_same_host(self, url):254 """255 Check if the given ``url`` is a member of the same host as this242- conncetion pool.256+ connection pool.257 """258 # TODO: Add optional support for socket.gethostbyname checking.259+ scheme, host, port = get_host(url)260+261+ if self.port and not port:262+ # Use explicit default port for comparison when none is given.263+ port = port_by_scheme.get(scheme)264+265 return (url.startswith('/') or246- get_host(url) == (self.scheme, self.host, self.port))266+ (scheme, host, port) == (self.scheme, self.host, self.port))267 268 def urlopen(self, method, url, body=None, headers=None, retries=3,269 redirect=True, assert_same_host=True, timeout=_Default,270 pool_timeout=None, release_conn=None, **response_kw):64 unmodified lines335 if headers is None:336 headers = self.headers337 338 if retries < 0:319- raise MaxRetryError(url)339+ raise MaxRetryError(self, url)340 341 if timeout is _Default:342 timeout = self.timeout343 5 unmodified lines349 host = "%s://%s" % (self.scheme, self.host)350 if self.port:351 host = "%s:%d" % (host, self.port)352 333- raise HostChangedError(host, url, retries - 1)353+ raise HostChangedError(self, url, retries - 1)354 355 conn = None356 357 try:24 unmodified lines382 # ``response.read()``)383 384 except Empty as e:385 # Timed out by queue366- raise TimeoutError("Request timed out. (pool_timeout=%s)" %386+ raise TimeoutError(self, "Request timed out. (pool_timeout=%s)" %387 pool_timeout)388 389 except SocketTimeout as e:390 # Timed out by socket371- raise TimeoutError("Request timed out. (timeout=%s)" %391+ raise TimeoutError(self, "Request timed out. (timeout=%s)" %392 timeout)393 394 except BaseSSLError as e:395 # SSL certificate error181 unmodified lines577 if scheme == 'https':578 return HTTPSConnectionPool(host, port=port, **kw)579 else:580 return HTTPConnectionPool(host, port=port, **kw)581+582+583+def is_connection_dropped(conn):584+ """585+ Returns True if the connection is dropped and should be closed.586+587+ :param conn:588+ ``HTTPConnection`` object.589+ """590+ # poll-based replacement to select([conn.sock], [], [], 0.0)[0]:591+ p = poll()592+ p.register(conn.sock, POLLIN)593+ for (fno, ev) in p.poll(0.0):594+ if fno == conn.sock.fileno():595+ # Either data is buffered (bad), or the connection is dropped.596+ return Truemodified:requests/packages/urllib3/exceptions.py+27 added-18 removed
2 unmodified lines3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 7-## Exceptions7+## Base Exceptions8 9 class HTTPError(Exception):10 "Base exception used by this module."11 pass12 13 14-class SSLError(Exception):14+class PoolError(HTTPError):15+ "Base exception for errors caused within a pool."16+ def __init__(self, pool, message):17+ self.pool = pool18+ HTTPError.__init__(self, "%s: %s" % (pool, message))19+20+21+class SSLError(HTTPError):22 "Raised when SSL certificate fails in an HTTPS connection."23 pass24 25 26+## Leaf Exceptions27+19-class MaxRetryError(HTTPError):28+class MaxRetryError(PoolError):29 "Raised when the maximum number of retries is exceeded."21- def __init__(self, url):22- HTTPError.__init__(self, "Max retries exceeded for url: %s" % url)30+ def __init__(self, pool, url):31+ PoolError.__init__(self, pool,32+ "Max retries exceeded with url: %s" % url)33+34 self.url = url35 36 26-class TimeoutError(HTTPError):27- "Raised when a socket timeout occurs."28- pass29-30-31-class HostChangedError(HTTPError):37+class HostChangedError(PoolError):38 "Raised when an existing pool gets a request for a foreign host."33- def __init__(self, original_host, new_url, retries=3):34- HTTPError.__init__(self,35- "Connection pool with host '%s' tried to open a foreign host: %s" %36- (original_host, new_url))39+ def __init__(self, pool, url, retries=3):40+ PoolError.__init__(self, pool,41+ "Tried to open a foreign host with url: %s" % url)42 38- self.original_host = original_host39- self.new_url = new_url43+ self.url = url44 self.retries = retries45 46 43-class EmptyPoolError(HTTPError):47+class TimeoutError(PoolError):48+ "Raised when a socket timeout occurs."49+ pass50+51+52+class EmptyPoolError(PoolError):53 "Raised when a pool runs out of connections and no more are allowed."54 passmodified:requests/packages/urllib3/filepost.py+3 added-4 removed
8 unmodified lines9 10 try:11 from mimetools import choose_boundary12 except ImportError:13- # I don't like using an undocumented function, but I don't yet know what it does14- from email.generator import _make_boundary as choose_boundary13+ from .packages.mimetools_choose_boundary import choose_boundary14 15 from io import BytesIO16 18-from . import six19-from .six import b17+from .packages import six18+from .packages.six import b19 20 writer = codecs.lookup('utf-8')[3]21 22 52 unmodified linesmodified:requests/packages/urllib3/poolmanager.py+2 added-7 removed
6 unmodified lines7 import logging8 9 from ._collections import RecentlyUsedContainer10 from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool11-from .connectionpool import get_host, connection_from_url11+from .connectionpool import get_host, connection_from_url, port_by_scheme12 from .exceptions import HostChangedError13 from .request import RequestMethods14 15 4 unmodified lines20 'http': HTTPConnectionPool,21 'https': HTTPSConnectionPool,22 }23 24-port_by_scheme = {25- 'http': 80,26- 'https': 443,27-}28-24 log = logging.getLogger(__name__)25 26 27 class PoolManager(RequestMethods):76 unmodified lines104 return conn.urlopen(method, url, **kw)105 106 except HostChangedError as e:107 kw['retries'] = e.retries # Persist retries countdown113- return self.urlopen(method, e.new_url, **kw)108+ return self.urlopen(method, e.url, **kw)109 110 111 class ProxyManager(RequestMethods):112 """16 unmodified linesmodified:requests/packages/urllib3/response.py+11 added-14 removed
65 unmodified lines66 self.reason = reason67 self.strict = strict68 69 self._decode_content = decode_content70- self._body = None70+ self._body = body if body and isinstance(body, basestring) else None71 self._fp = None72 self._original_response = original_response73 74 self._pool = pool1 unmodified line76 77 if hasattr(body, 'read'):78 self._fp = body79 80- if preload_content:80+ if preload_content and not self._body:81 self._body = self.read(decode_content=decode_content)82 83 def get_redirect_location(self):84 """49 unmodified lines134 decoder = self.CONTENT_DECODERS.get(content_encoding)135 if decode_content is None:136 decode_content = self._decode_content137 138- data = self._fp and self._fp.read(amt)138+ if self._fp is None:139+ return140 141 try:142+ if amt is None:143+ # cStringIO doesn't like amt=None144+ data = self._fp.read()145+ else:146+ return self._fp.read(amt)147 142- if amt:143- return data144-145- if not decode_content or not decoder:146- if cache_content:147- self._body = data148-149- return data150-148 try:149+ if decode_content and decoder:152- data = decoder(data)150+ data = decoder(data)151 except IOError:152 raise HTTPError("Received response with content-encoding: %s, but "153 "failed to decode it." % content_encoding)154 2 unmodified lines157 158 return data159 160 finally:163-161 if self._original_response and self._original_response.isclosed():162 self.release_conn()163 164 @classmethod27 unmodified linesdeleted:requests/packages/urllib3/six.py-372 removed
1-"""Utilities for writing code that runs on Python 2 and 3"""2-3-#Copyright (c) 2010-2011 Benjamin Peterson4-5-#Permission is hereby granted, free of charge, to any person obtaining a copy of6-#this software and associated documentation files (the "Software"), to deal in7-#the Software without restriction, including without limitation the rights to8-#use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of9-#the Software, and to permit persons to whom the Software is furnished to do so,10-#subject to the following conditions:11-12-#The above copyright notice and this permission notice shall be included in all13-#copies or substantial portions of the Software.14-15-#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR16-#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS17-#FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR18-#COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER19-#IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN20-#CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.21-22-import operator23-import sys24-import types25-26-__author__ = "Benjamin Peterson <benjamin@python.org>"27-__version__ = "1.1.0"28-29-30-# True if we are running on Python 3.31-PY3 = sys.version_info[0] == 332-33-if PY3:34- string_types = str,35- integer_types = int,36- class_types = type,37- text_type = str38- binary_type = bytes39-40- MAXSIZE = sys.maxsize41-else:42- string_types = basestring,43- integer_types = (int, long)44- class_types = (type, types.ClassType)45- text_type = unicode46- binary_type = str47-48- # It's possible to have sizeof(long) != sizeof(Py_ssize_t).49- class X(object):50- def __len__(self):51- return 1 << 3152- try:53- len(X())54- except OverflowError:55- # 32-bit56- MAXSIZE = int((1 << 31) - 1)57- else:58- # 64-bit59- MAXSIZE = int((1 << 63) - 1)60- del X61-62-63-def _add_doc(func, doc):64- """Add documentation to a function."""65- func.__doc__ = doc66-67-68-def _import_module(name):69- """Import module, returning the module after the last dot."""70- __import__(name)71- return sys.modules[name]72-73-74-class _LazyDescr(object):75-76- def __init__(self, name):77- self.name = name78-79- def __get__(self, obj, tp):80- result = self._resolve()81- setattr(obj, self.name, result)82- # This is a bit ugly, but it avoids running this again.83- delattr(tp, self.name)84- return result85-86-87-class MovedModule(_LazyDescr):88-89- def __init__(self, name, old, new=None):90- super(MovedModule, self).__init__(name)91- if PY3:92- if new is None:93- new = name94- self.mod = new95- else:96- self.mod = old97-98- def _resolve(self):99- return _import_module(self.mod)100-101-102-class MovedAttribute(_LazyDescr):103-104- def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):105- super(MovedAttribute, self).__init__(name)106- if PY3:107- if new_mod is None:108- new_mod = name109- self.mod = new_mod110- if new_attr is None:111- if old_attr is None:112- new_attr = name113- else:114- new_attr = old_attr115- self.attr = new_attr116- else:117- self.mod = old_mod118- if old_attr is None:119- old_attr = name120- self.attr = old_attr121-122- def _resolve(self):123- module = _import_module(self.mod)124- return getattr(module, self.attr)125-126-127-128-class _MovedItems(types.ModuleType):129- """Lazy loading of moved objects"""130-131-132-_moved_attributes = [133- MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),134- MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),135- MovedAttribute("map", "itertools", "builtins", "imap", "map"),136- MovedAttribute("reload_module", "__builtin__", "imp", "reload"),137- MovedAttribute("reduce", "__builtin__", "functools"),138- MovedAttribute("StringIO", "StringIO", "io"),139- MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),140- MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),141-142- MovedModule("builtins", "__builtin__"),143- MovedModule("configparser", "ConfigParser"),144- MovedModule("copyreg", "copy_reg"),145- MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),146- MovedModule("http_cookies", "Cookie", "http.cookies"),147- MovedModule("html_entities", "htmlentitydefs", "html.entities"),148- MovedModule("html_parser", "HTMLParser", "html.parser"),149- MovedModule("http_client", "httplib", "http.client"),150- MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),151- MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),152- MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),153- MovedModule("cPickle", "cPickle", "pickle"),154- MovedModule("queue", "Queue"),155- MovedModule("reprlib", "repr"),156- MovedModule("socketserver", "SocketServer"),157- MovedModule("tkinter", "Tkinter"),158- MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),159- MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),160- MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),161- MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),162- MovedModule("tkinter_tix", "Tix", "tkinter.tix"),163- MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),164- MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),165- MovedModule("tkinter_colorchooser", "tkColorChooser",166- "tkinter.colorchooser"),167- MovedModule("tkinter_commondialog", "tkCommonDialog",168- "tkinter.commondialog"),169- MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),170- MovedModule("tkinter_font", "tkFont", "tkinter.font"),171- MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),172- MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",173- "tkinter.simpledialog"),174- MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),175- MovedModule("winreg", "_winreg"),176-]177-for attr in _moved_attributes:178- setattr(_MovedItems, attr.name, attr)179-del attr180-181-moves = sys.modules["six.moves"] = _MovedItems("moves")182-183-184-def add_move(move):185- """Add an item to six.moves."""186- setattr(_MovedItems, move.name, move)187-188-189-def remove_move(name):190- """Remove item from six.moves."""191- try:192- delattr(_MovedItems, name)193- except AttributeError:194- try:195- del moves.__dict__[name]196- except KeyError:197- raise AttributeError("no such move, %r" % (name,))198-199-200-if PY3:201- _meth_func = "__func__"202- _meth_self = "__self__"203-204- _func_code = "__code__"205- _func_defaults = "__defaults__"206-207- _iterkeys = "keys"208- _itervalues = "values"209- _iteritems = "items"210-else:211- _meth_func = "im_func"212- _meth_self = "im_self"213-214- _func_code = "func_code"215- _func_defaults = "func_defaults"216-217- _iterkeys = "iterkeys"218- _itervalues = "itervalues"219- _iteritems = "iteritems"220-221-222-if PY3:223- def get_unbound_function(unbound):224- return unbound225-226-227- advance_iterator = next228-229- def callable(obj):230- return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)231-else:232- def get_unbound_function(unbound):233- return unbound.im_func234-235-236- def advance_iterator(it):237- return it.next()238-239- callable = callable240-_add_doc(get_unbound_function,241- """Get the function out of a possibly unbound function""")242-243-244-get_method_function = operator.attrgetter(_meth_func)245-get_method_self = operator.attrgetter(_meth_self)246-get_function_code = operator.attrgetter(_func_code)247-get_function_defaults = operator.attrgetter(_func_defaults)248-249-250-def iterkeys(d):251- """Return an iterator over the keys of a dictionary."""252- return getattr(d, _iterkeys)()253-254-def itervalues(d):255- """Return an iterator over the values of a dictionary."""256- return getattr(d, _itervalues)()257-258-def iteritems(d):259- """Return an iterator over the (key, value) pairs of a dictionary."""260- return getattr(d, _iteritems)()261-262-263-if PY3:264- def b(s):265- return s.encode("latin-1")266- def u(s):267- return s268- if sys.version_info[1] <= 1:269- def int2byte(i):270- return bytes((i,))271- else:272- # This is about 2x faster than the implementation above on 3.2+273- int2byte = operator.methodcaller("to_bytes", 1, "big")274- import io275- StringIO = io.StringIO276- BytesIO = io.BytesIO277-else:278- def b(s):279- return s280- def u(s):281- return unicode(s, "unicode_escape")282- int2byte = chr283- import StringIO284- StringIO = BytesIO = StringIO.StringIO285-_add_doc(b, """Byte literal""")286-_add_doc(u, """Text literal""")287-288-289-if PY3:290- import builtins291- exec_ = getattr(builtins, "exec")292-293-294- def reraise(tp, value, tb=None):295- if value.__traceback__ is not tb:296- raise value.with_traceback(tb)297- raise value298-299-300- print_ = getattr(builtins, "print")301- del builtins302-303-else:304- def exec_(code, globs=None, locs=None):305- """Execute code in a namespace."""306- if globs is None:307- frame = sys._getframe(1)308- globs = frame.f_globals309- if locs is None:310- locs = frame.f_locals311- del frame312- elif locs is None:313- locs = globs314- exec("""exec code in globs, locs""")315-316-317- exec_("""def reraise(tp, value, tb=None):318- raise tp, value, tb319-""")320-321-322- def print_(*args, **kwargs):323- """The new-style print function."""324- fp = kwargs.pop("file", sys.stdout)325- if fp is None:326- return327- def write(data):328- if not isinstance(data, basestring):329- data = str(data)330- fp.write(data)331- want_unicode = False332- sep = kwargs.pop("sep", None)333- if sep is not None:334- if isinstance(sep, unicode):335- want_unicode = True336- elif not isinstance(sep, str):337- raise TypeError("sep must be None or a string")338- end = kwargs.pop("end", None)339- if end is not None:340- if isinstance(end, unicode):341- want_unicode = True342- elif not isinstance(end, str):343- raise TypeError("end must be None or a string")344- if kwargs:345- raise TypeError("invalid keyword arguments to print()")346- if not want_unicode:347- for arg in args:348- if isinstance(arg, unicode):349- want_unicode = True350- break351- if want_unicode:352- newline = unicode("\n")353- space = unicode(" ")354- else:355- newline = "\n"356- space = " "357- if sep is None:358- sep = space359- if end is None:360- end = newline361- for i, arg in enumerate(args):362- if i:363- write(sep)364- write(arg)365- write(end)366-367-_add_doc(reraise, """Reraise an exception.""")368-369-370-def with_metaclass(meta, base=object):371- """Create a base class with a metaclass."""372- return meta("NewBase", (base,), {})