diff options
author | Jason R. Coombs <jaraco@jaraco.com> | 2016-06-05 17:36:38 -0400 |
---|---|---|
committer | Jason R. Coombs <jaraco@jaraco.com> | 2016-06-05 17:36:38 -0400 |
commit | 86e928d458ca501a601ea1c7f25f8add2855c336 (patch) | |
tree | b16fcd2c8174e61249c9914db36dcee98a6e9972 /cherrypy | |
parent | 0a0b2e0f109caf003d2cc32cadbcbaa094de7d33 (diff) | |
download | cherrypy-git-86e928d458ca501a601ea1c7f25f8add2855c336.tar.gz |
Rely on six for Python 3 differentiation
Diffstat (limited to 'cherrypy')
-rw-r--r-- | cherrypy/_cpcompat.py | 10 | ||||
-rw-r--r-- | cherrypy/_cplogging.py | 21 | ||||
-rw-r--r-- | cherrypy/_cprequest.py | 18 | ||||
-rw-r--r-- | cherrypy/_cpserver.py | 10 | ||||
-rw-r--r-- | cherrypy/_cptree.py | 8 | ||||
-rw-r--r-- | cherrypy/_cpwsgi.py | 16 | ||||
-rw-r--r-- | cherrypy/_helper.py | 6 | ||||
-rw-r--r-- | cherrypy/test/test_compat.py | 4 | ||||
-rw-r--r-- | cherrypy/test/test_config.py | 6 | ||||
-rw-r--r-- | cherrypy/test/test_conn.py | 4 | ||||
-rw-r--r-- | cherrypy/test/test_http.py | 8 | ||||
-rw-r--r-- | cherrypy/test/test_logging.py | 12 | ||||
-rw-r--r-- | cherrypy/test/test_tools.py | 8 | ||||
-rw-r--r-- | cherrypy/test/test_tutorials.py | 4 | ||||
-rw-r--r-- | cherrypy/test/test_xmlrpc.py | 5 | ||||
-rw-r--r-- | cherrypy/test/webtest.py | 12 |
16 files changed, 86 insertions, 66 deletions
diff --git a/cherrypy/_cpcompat.py b/cherrypy/_cpcompat.py index a73feb0b..5f4133b0 100644 --- a/cherrypy/_cpcompat.py +++ b/cherrypy/_cpcompat.py @@ -20,8 +20,9 @@ import re import sys import threading -if sys.version_info >= (3, 0): - py3k = True +import six + +if six.PY3: bytestr = bytes unicodestr = str nativestr = unicodestr @@ -55,7 +56,6 @@ if sys.version_info >= (3, 0): from io import BytesIO as BytesIO else: # Python 2 - py3k = False bytestr = str unicodestr = unicode nativestr = bytestr @@ -221,7 +221,7 @@ except ImportError: from http.server import BaseHTTPRequestHandler # Some platforms don't expose HTTPSConnection, so handle it separately -if py3k: +if six.PY3: try: from http.client import HTTPSConnection except ImportError: @@ -300,7 +300,7 @@ except ImportError: def _json_encode(s): raise ValueError('No JSON library is available') finally: - if json and py3k: + if json and six.PY3: # The two Python 3 implementations (simplejson/json) # outputs str. We need bytes. def json_encode(value): diff --git a/cherrypy/_cplogging.py b/cherrypy/_cplogging.py index 19d1d91e..b13b49e6 100644 --- a/cherrypy/_cplogging.py +++ b/cherrypy/_cplogging.py @@ -115,9 +115,11 @@ logfmt = logging.Formatter("%(message)s") import os import sys +import six + import cherrypy from cherrypy import _cperror -from cherrypy._cpcompat import ntob, py3k +from cherrypy._cpcompat import ntob class NullHandler(logging.Handler): @@ -151,12 +153,11 @@ class LogManager(object): access_log = None """The actual :class:`logging.Logger` instance for access messages.""" - if py3k: - access_log_format = \ - '{h} {l} {u} {t} "{r}" {s} {b} "{f}" "{a}"' - else: - access_log_format = \ - '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"' + access_log_format = ( + '{h} {l} {u} {t} "{r}" {s} {b} "{f}" "{a}"' + if six.PY3 else + '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"' + ) logger_root = None """The "top-level" logger name. @@ -246,7 +247,7 @@ class LogManager(object): status = "-" else: status = response.output_status.split(ntob(" "), 1)[0] - if py3k: + if six.PY3: status = status.decode('ISO-8859-1') atoms = {'h': remote.name or remote.ip, @@ -260,7 +261,7 @@ class LogManager(object): 'a': dict.get(inheaders, 'User-Agent', ''), 'o': dict.get(inheaders, 'Host', '-'), } - if py3k: + if six.PY3: for k, v in atoms.items(): if not isinstance(v, str): v = str(v) @@ -284,7 +285,7 @@ class LogManager(object): self(traceback=True) else: for k, v in atoms.items(): - if isinstance(v, unicode): + if isinstance(v, six.text_type): v = v.encode('utf8') elif not isinstance(v, str): v = str(v) diff --git a/cherrypy/_cprequest.py b/cherrypy/_cprequest.py index 290bd2eb..4b0db1c2 100644 --- a/cherrypy/_cprequest.py +++ b/cherrypy/_cprequest.py @@ -1,12 +1,12 @@ - -import os import sys import time import warnings +import six + import cherrypy from cherrypy._cpcompat import basestring, copykeys, ntob, unicodestr -from cherrypy._cpcompat import SimpleCookie, CookieError, py3k +from cherrypy._cpcompat import SimpleCookie, CookieError from cherrypy import _cpreqbody, _cpconfig from cherrypy._cperror import format_exc, bare_error from cherrypy.lib import httputil, file_generator @@ -701,9 +701,9 @@ class Request(object): self.query_string_encoding) # Python 2 only: keyword arguments must be byte strings (type 'str'). - if not py3k: + if six.PY2: for key, value in p.items(): - if isinstance(key, unicode): + if isinstance(key, six.text_type): del p[key] p[key.encode(self.query_string_encoding)] = value self.params.update(p) @@ -799,7 +799,7 @@ class ResponseBody(object): """The body of the HTTP response (the response entity).""" - if py3k: + if six.PY3: unicode_err = ("Page handlers MUST return bytes. Use tools.encode " "if you wish to return unicode.") @@ -812,7 +812,7 @@ class ResponseBody(object): def __set__(self, obj, value): # Convert the given value to an iterable object. - if py3k and isinstance(value, str): + if six.PY3 and isinstance(value, str): raise ValueError(self.unicode_err) if isinstance(value, basestring): @@ -824,7 +824,7 @@ class ResponseBody(object): else: # [''] doesn't evaluate to False, so replace it with []. value = [] - elif py3k and isinstance(value, list): + elif six.PY3 and isinstance(value, list): # every item in a list must be bytes... for i, item in enumerate(value): if isinstance(item, str): @@ -906,7 +906,7 @@ class Response(object): newbody = [] for chunk in self.body: - if py3k and not isinstance(chunk, bytes): + if six.PY3 and not isinstance(chunk, bytes): raise TypeError("Chunk %s is not of type 'bytes'." % repr(chunk)) newbody.append(chunk) diff --git a/cherrypy/_cpserver.py b/cherrypy/_cpserver.py index a31e7428..e47085cd 100644 --- a/cherrypy/_cpserver.py +++ b/cherrypy/_cpserver.py @@ -1,10 +1,10 @@ """Manage HTTP servers with CherryPy.""" -import warnings +import six import cherrypy from cherrypy.lib import attributes -from cherrypy._cpcompat import basestring, py3k +from cherrypy._cpcompat import basestring # We import * because we want to export check_port # et al as attributes of this module. @@ -61,11 +61,11 @@ class Server(ServerAdapter): socket_timeout = 10 """The timeout in seconds for accepted connections (default 10).""" - + accepted_queue_size = -1 """The maximum number of requests which will be queued up before the server refuses to accept it (default -1, meaning no limit).""" - + accepted_queue_timeout = 10 """The timeout in seconds for attempting to add a request to the queue when the queue is full (default 10).""" @@ -113,7 +113,7 @@ class Server(ServerAdapter): ssl_private_key = None """The filename of the private key to use with SSL.""" - if py3k: + if six.PY3: ssl_module = 'builtin' """The name of a registered SSL adaptation module to use with the builtin WSGI server. Builtin options are: 'builtin' (to diff --git a/cherrypy/_cptree.py b/cherrypy/_cptree.py index 6c434039..c40e3b33 100644 --- a/cherrypy/_cptree.py +++ b/cherrypy/_cptree.py @@ -2,8 +2,10 @@ import os +import six + import cherrypy -from cherrypy._cpcompat import ntou, py3k +from cherrypy._cpcompat import ntou from cherrypy import _cpconfig, _cplogging, _cprequest, _cpwsgi, tools from cherrypy.lib import httputil @@ -261,7 +263,7 @@ class Tree(object): # to '' (some WSGI servers always set SCRIPT_NAME to ''). # Try to look up the app using the full path. env1x = environ - if not py3k and environ.get(ntou('wsgi.version')) == (ntou('u'), 0): + if six.PY2 and environ.get(ntou('wsgi.version')) == (ntou('u'), 0): env1x = _cpwsgi.downgrade_wsgi_ux_to_1x(environ) path = httputil.urljoin(env1x.get('SCRIPT_NAME', ''), env1x.get('PATH_INFO', '')) @@ -274,7 +276,7 @@ class Tree(object): # Correct the SCRIPT_NAME and PATH_INFO environ entries. environ = environ.copy() - if not py3k and environ.get(ntou('wsgi.version')) == (ntou('u'), 0): + if six.PY2 and environ.get(ntou('wsgi.version')) == (ntou('u'), 0): # Python 2/WSGI u.0: all strings MUST be of type unicode enc = environ[ntou('wsgi.url_encoding')] environ[ntou('SCRIPT_NAME')] = sn.decode(enc) diff --git a/cherrypy/_cpwsgi.py b/cherrypy/_cpwsgi.py index ce913950..610ea7db 100644 --- a/cherrypy/_cpwsgi.py +++ b/cherrypy/_cpwsgi.py @@ -9,8 +9,10 @@ still be translatable to bytes via the Latin-1 encoding!" import sys as _sys +import six + import cherrypy as _cherrypy -from cherrypy._cpcompat import BytesIO, bytestr, ntob, ntou, py3k, unicodestr +from cherrypy._cpcompat import BytesIO, bytestr, ntob, ntou, unicodestr from cherrypy import _cperror from cherrypy.lib import httputil from cherrypy.lib import is_closable_iterator @@ -168,7 +170,7 @@ class _TrappedResponse(object): return self.trap(next, self.iter_response) # todo: https://pythonhosted.org/six/#six.Iterator - if not py3k: + if six.PY2: next = __next__ def close(self): @@ -189,7 +191,7 @@ class _TrappedResponse(object): if not _cherrypy.request.show_tracebacks: tb = "" s, h, b = _cperror.bare_error(tb) - if py3k: + if six.PY3: # What fun. s = s.decode('ISO-8859-1') h = [(k.decode('ISO-8859-1'), v.decode('ISO-8859-1')) @@ -227,7 +229,7 @@ class AppResponse(object): def __init__(self, environ, start_response, cpapp): self.cpapp = cpapp try: - if not py3k: + if six.PY2: if environ.get(ntou('wsgi.version')) == (ntou('u'), 0): environ = downgrade_wsgi_ux_to_1x(environ) self.environ = environ @@ -251,7 +253,7 @@ class AppResponse(object): v) outheaders.append((k, v)) - if py3k: + if six.PY3: # According to PEP 3333, when using Python 3, the response # status and headers must be bytes masquerading as unicode; # that is, they must be of type "str" but are restricted to @@ -273,7 +275,7 @@ class AppResponse(object): return next(self.iter_response) # todo: https://pythonhosted.org/six/#six.Iterator - if not py3k: + if six.PY2: next = __next__ def close(self): @@ -321,7 +323,7 @@ class AppResponse(object): self.environ.get('PATH_INFO', '')) qs = self.environ.get('QUERY_STRING', '') - if py3k: + if six.PY3: # This isn't perfect; if the given PATH_INFO is in the # wrong encoding, it may fail to match the appropriate config # section URI. But meh. diff --git a/cherrypy/_helper.py b/cherrypy/_helper.py index 56bc1a25..970e2a4a 100644 --- a/cherrypy/_helper.py +++ b/cherrypy/_helper.py @@ -2,8 +2,10 @@ Helper functions for CP apps """ +import six + from cherrypy._cpcompat import urljoin as _urljoin, urlencode as _urlencode -from cherrypy._cpcompat import basestring, py3k +from cherrypy._cpcompat import basestring import cherrypy @@ -25,7 +27,7 @@ def expose(func=None, alias=None): import sys import types decoratable_types = types.FunctionType, types.MethodType, type, - if not py3k: + if six.PY2: # Old-style classes are type types.ClassType. decoratable_types += types.ClassType, if isinstance(func, decoratable_types): diff --git a/cherrypy/test/test_compat.py b/cherrypy/test/test_compat.py index 62cb3b4f..90da8b02 100644 --- a/cherrypy/test/test_compat.py +++ b/cherrypy/test/test_compat.py @@ -1,5 +1,7 @@ import unittest +import six + import nose from cherrypy import _cpcompat as compat @@ -14,6 +16,6 @@ class StringTester(unittest.TestCase): See #1132 for discussion. """ - if compat.py3k: + if six.PY3: raise nose.SkipTest("Only useful on Python 2") self.assertRaises(Exception, compat.ntob, unicode('fight')) diff --git a/cherrypy/test/test_config.py b/cherrypy/test/test_config.py index 6a48a846..ab736803 100644 --- a/cherrypy/test/test_config.py +++ b/cherrypy/test/test_config.py @@ -4,6 +4,8 @@ import os import sys import unittest +import six + import cherrypy import cherrypy._cpcompat as compat @@ -102,7 +104,7 @@ def setup_server(): return num + 1 incr._cp_config = {'raw.input.map': {'num': int}} - if not compat.py3k: + if not six.PY3: thing3 = "thing3: unicode('test', errors='ignore')" else: thing3 = '' @@ -202,7 +204,7 @@ class ConfigTests(helper.CPWebCase): from cherrypy.tutorial import thing2 self.assertBody(repr(thing2)) - if not compat.py3k: + if not six.PY3: self.getPage("/repr?key=thing3") self.assertBody(repr(unicode('test'))) diff --git a/cherrypy/test/test_conn.py b/cherrypy/test/test_conn.py index e5a02ec6..57c69423 100644 --- a/cherrypy/test/test_conn.py +++ b/cherrypy/test/test_conn.py @@ -5,6 +5,7 @@ import sys import time import errno +import six import cherrypy from cherrypy._cpcompat import HTTPConnection, HTTPSConnection, NotConnected @@ -14,7 +15,6 @@ from cherrypy._cpcompat import ( tonative, urlopen, unicodestr, - py3k ) from cherrypy.test import webtest @@ -445,7 +445,7 @@ class PipelineTests(helper.CPWebCase): # ``conn.sock``. Until that bug get's fixed we will # monkey patch the ``reponse`` instance. # https://bugs.python.org/issue23377 - if py3k: + if six.PY3: response.fp = conn.sock.makefile("rb", 0) response.begin() body = response.read(13) diff --git a/cherrypy/test/test_http.py b/cherrypy/test/test_http.py index a6bc5614..6511ff4f 100644 --- a/cherrypy/test/test_http.py +++ b/cherrypy/test/test_http.py @@ -5,10 +5,12 @@ import mimetypes import socket import sys +import six + from mock import patch import cherrypy -from cherrypy._cpcompat import HTTPConnection, HTTPSConnection, ntob, py3k +from cherrypy._cpcompat import HTTPConnection, HTTPSConnection, ntob def encode_multipart_formdata(files): @@ -70,13 +72,13 @@ class HTTPTests(helper.CPWebCase): count += 1 else: if count: - if py3k: + if six.PY3: curchar = chr(curchar) summary.append("%s * %d" % (curchar, count)) count = 1 curchar = c if count: - if py3k: + if six.PY3: curchar = chr(curchar) summary.append("%s * %d" % (curchar, count)) return ", ".join(summary) diff --git a/cherrypy/test/test_logging.py b/cherrypy/test/test_logging.py index 0ae26626..2a910644 100644 --- a/cherrypy/test/test_logging.py +++ b/cherrypy/test/test_logging.py @@ -3,8 +3,10 @@ import os localDir = os.path.dirname(__file__) +import six + import cherrypy -from cherrypy._cpcompat import ntob, ntou, py3k +from cherrypy._cpcompat import ntob, ntou access_log = os.path.join(localDir, "access.log") error_log = os.path.join(localDir, "error.log") @@ -112,7 +114,7 @@ class AccessLogTests(helper.CPWebCase, logtest.LogCase): original_logformat = cherrypy._cplogging.LogManager.access_log_format cherrypy._cplogging.LogManager.access_log_format = \ '{h} {l} {u} {t} "{r}" {s} {b} "{f}" "{a}" {o}' \ - if py3k else \ + if six.PY3 else \ '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(o)s' self.markLog() @@ -130,8 +132,8 @@ class AccessLogTests(helper.CPWebCase, logtest.LogCase): self.markLog() self.getPage("/uni_code") self.assertStatus(200) - if py3k: - # The repr of a bytestring in py3k includes a b'' prefix + if six.PY3: + # The repr of a bytestring in six.PY3 includes a b'' prefix self.assertLog(-1, repr(tartaros.encode('utf8'))[2:-1]) else: self.assertLog(-1, repr(tartaros.encode('utf8'))[1:-1]) @@ -143,7 +145,7 @@ class AccessLogTests(helper.CPWebCase, logtest.LogCase): self.markLog() self.getPage("/slashes") self.assertStatus(200) - if py3k: + if six.PY3: self.assertLog(-1, ntob('"GET /slashed\\path HTTP/1.1"')) else: self.assertLog(-1, r'"GET /slashed\\path HTTP/1.1"') diff --git a/cherrypy/test/test_tools.py b/cherrypy/test/test_tools.py index cac85ae8..c967f560 100644 --- a/cherrypy/test/test_tools.py +++ b/cherrypy/test/test_tools.py @@ -4,12 +4,14 @@ import gzip import sys import unittest from cherrypy._cpcompat import BytesIO, copyitems, itervalues -from cherrypy._cpcompat import IncompleteRead, ntob, ntou, py3k, xrange +from cherrypy._cpcompat import IncompleteRead, ntob, ntou, xrange from cherrypy._cpcompat import bytestr, unicodestr import time timeout = 0.2 import types +import six + import cherrypy from cherrypy import tools @@ -101,7 +103,7 @@ class ToolTests(helper.CPWebCase): def __call__(self, scale): r = cherrypy.response r.collapse_body() - if py3k: + if six.PY3: r.body = [bytes([(x + scale) % 256 for x in r.body[0]])] else: r.body = [chr((ord(x) + scale) % 256) for x in r.body[0]] @@ -371,7 +373,7 @@ class ToolTests(helper.CPWebCase): # but it proves the priority was changed. self.getPage("/decorated_euro/subpath", headers=[("Accept-Encoding", "gzip")]) - if py3k: + if six.PY3: self.assertInBody(bytes([(x + 3) % 256 for x in zbuf.getvalue()])) else: self.assertInBody(''.join([chr((ord(x) + 3) % 256) diff --git a/cherrypy/test/test_tutorials.py b/cherrypy/test/test_tutorials.py index f75026cb..bfcd50f7 100644 --- a/cherrypy/test/test_tutorials.py +++ b/cherrypy/test/test_tutorials.py @@ -8,7 +8,7 @@ except Exception: # Python 2.6 may not have it. pass -from cherrypy._cpcompat import py3k +import six import cherrypy from cherrypy.test import helper @@ -46,7 +46,7 @@ class TutorialTest(helper.CPWebCase): root = getattr(module, root_name) conf = getattr(module, 'tutconf') class_types = type, - if not py3k: + if six.PY2: class_types += types.ClassType, if isinstance(root, class_types): root = root() diff --git a/cherrypy/test/test_xmlrpc.py b/cherrypy/test/test_xmlrpc.py index 067000db..e95d5d79 100644 --- a/cherrypy/test/test_xmlrpc.py +++ b/cherrypy/test/test_xmlrpc.py @@ -1,5 +1,6 @@ import sys -from cherrypy._cpcompat import py3k + +import six try: from xmlrpclib import DateTime, Fault, ProtocolError, ServerProxy @@ -8,7 +9,7 @@ except ImportError: from xmlrpc.client import DateTime, Fault, ProtocolError, ServerProxy from xmlrpc.client import SafeTransport -if py3k: +if six.PY3: HTTPSTransport = SafeTransport # Python 3.0's SafeTransport still mistakenly checks for socket.ssl diff --git a/cherrypy/test/webtest.py b/cherrypy/test/webtest.py index bb62bb93..9da54700 100644 --- a/cherrypy/test/webtest.py +++ b/cherrypy/test/webtest.py @@ -29,7 +29,9 @@ import json from unittest import * from unittest import _TextTestResult -from cherrypy._cpcompat import basestring, ntob, py3k, HTTPConnection +import six + +from cherrypy._cpcompat import basestring, ntob, HTTPConnection from cherrypy._cpcompat import HTTPSConnection, unicodestr @@ -125,12 +127,12 @@ class ReloadingTestLoader(TestLoader): if isinstance(obj, types.ModuleType): return self.loadTestsFromModule(obj) - elif (((py3k and isinstance(obj, type)) + elif (((six.PY3 and isinstance(obj, type)) or isinstance(obj, (type, types.ClassType))) and issubclass(obj, TestCase)): return self.loadTestsFromTestCase(obj) elif isinstance(obj, types.UnboundMethodType): - if py3k: + if six.PY3: return obj.__self__.__class__(obj.__name__) else: return obj.im_class(obj.__name__) @@ -499,7 +501,7 @@ def cleanHeaders(headers, method, body, host, port): def shb(response): """Return status, headers, body the way we like from a response.""" - if py3k: + if six.PY3: h = response.getheaders() else: h = [] @@ -546,7 +548,7 @@ def openURL(url, headers=None, method="GET", body=None, conn._http_vsn_str = protocol conn._http_vsn = int("".join([x for x in protocol if x.isdigit()])) - if py3k and isinstance(url, bytes): + if six.PY3 and isinstance(url, bytes): url = url.decode() conn.putrequest(method.upper(), url, skip_host=True, skip_accept_encoding=True) |