Skip to content

Commit d8213f2

Browse files
committed
Remove reliance on six
1 parent 919637b commit d8213f2

50 files changed

Lines changed: 125 additions & 416 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

cherrypy/_cpchecker.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
"""Checker for CherryPy sites and mounted apps."""
22
import os
33
import warnings
4-
5-
import six
6-
from six.moves import builtins
4+
import builtins
75

86
import cherrypy
97

@@ -70,14 +68,14 @@ def check_app_config_entries_dont_start_with_script_name(self):
7068

7169
def check_site_config_entries_in_app_config(self):
7270
"""Check for mounted Applications that have site-scoped config."""
73-
for sn, app in six.iteritems(cherrypy.tree.apps):
71+
for sn, app in cherrypy.tree.apps.items():
7472
if not isinstance(app, cherrypy.Application):
7573
continue
7674

7775
msg = []
78-
for section, entries in six.iteritems(app.config):
76+
for section, entries in app.config.items():
7977
if section.startswith('/'):
80-
for key, value in six.iteritems(entries):
78+
for key, value in entries.items():
8179
for n in ('engine.', 'server.', 'tree.', 'checker.'):
8280
if key.startswith(n):
8381
msg.append('[%s] %s = %s' %

cherrypy/_cpcompat.py

Lines changed: 9 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,13 @@
1818
and their .encode/.decode methods as needed.
1919
"""
2020

21-
import re
2221
import sys
2322
import threading
23+
import urllib.parse
24+
import http.client
2425

25-
import six
26-
from six.moves import urllib
2726

28-
29-
if six.PY3:
27+
if True:
3028
def ntob(n, encoding='ISO-8859-1'):
3129
"""Return the given native string as a byte string in the given
3230
encoding.
@@ -49,43 +47,6 @@ def tonative(n, encoding='ISO-8859-1'):
4947
if isinstance(n, bytes):
5048
return n.decode(encoding)
5149
return n
52-
else:
53-
# Python 2
54-
def ntob(n, encoding='ISO-8859-1'):
55-
"""Return the given native string as a byte string in the given
56-
encoding.
57-
"""
58-
assert_native(n)
59-
# In Python 2, the native string type is bytes. Assume it's already
60-
# in the given encoding, which for ISO-8859-1 is almost always what
61-
# was intended.
62-
return n
63-
64-
def ntou(n, encoding='ISO-8859-1'):
65-
"""Return the given native string as a unicode string with the given
66-
encoding.
67-
"""
68-
assert_native(n)
69-
# In Python 2, the native string type is bytes.
70-
# First, check for the special encoding 'escape'. The test suite uses
71-
# this to signal that it wants to pass a string with embedded \uXXXX
72-
# escapes, but without having to prefix it with u'' for Python 2,
73-
# but no prefix for Python 3.
74-
if encoding == 'escape':
75-
return six.text_type( # unicode for Python 2
76-
re.sub(r'\\u([0-9a-zA-Z]{4})',
77-
lambda m: six.unichr(int(m.group(1), 16)),
78-
n.decode('ISO-8859-1')))
79-
# Assume it's already in the given encoding, which for ISO-8859-1
80-
# is almost always what was intended.
81-
return n.decode(encoding)
82-
83-
def tonative(n, encoding='ISO-8859-1'):
84-
"""Return the given string as a native string in the given encoding."""
85-
# In Python 2, the native string type is bytes.
86-
if isinstance(n, six.text_type): # unicode for Python 2
87-
return n.encode(encoding)
88-
return n
8950

9051

9152
def assert_native(n):
@@ -94,24 +55,12 @@ def assert_native(n):
9455

9556

9657
# Some platforms don't expose HTTPSConnection, so handle it separately
97-
HTTPSConnection = getattr(six.moves.http_client, 'HTTPSConnection', None)
98-
58+
HTTPSConnection = getattr(http.client, 'HTTPSConnection', None)
9959

100-
def _unquote_plus_compat(string, encoding='utf-8', errors='replace'):
101-
return urllib.parse.unquote_plus(string).decode(encoding, errors)
10260

103-
104-
def _unquote_compat(string, encoding='utf-8', errors='replace'):
105-
return urllib.parse.unquote(string).decode(encoding, errors)
106-
107-
108-
def _quote_compat(string, encoding='utf-8', errors='replace'):
109-
return urllib.parse.quote(string.encode(encoding, errors))
110-
111-
112-
unquote_plus = urllib.parse.unquote_plus if six.PY3 else _unquote_plus_compat
113-
unquote = urllib.parse.unquote if six.PY3 else _unquote_compat
114-
quote = urllib.parse.quote if six.PY3 else _quote_compat
61+
unquote_plus = urllib.parse.unquote_plus
62+
unquote = urllib.parse.unquote
63+
quote = urllib.parse.quote
11564

11665
try:
11766
# Prefer simplejson
@@ -124,16 +73,14 @@ def _quote_compat(string, encoding='utf-8', errors='replace'):
12473
_json_encode = json.JSONEncoder().iterencode
12574

12675

127-
if six.PY3:
76+
if True:
12877
# Encode to bytes on Python 3
12978
def json_encode(value):
13079
for chunk in _json_encode(value):
13180
yield chunk.encode('utf-8')
132-
else:
133-
json_encode = _json_encode
13481

13582

136-
text_or_bytes = six.text_type, bytes
83+
text_or_bytes = str, bytes
13784

13885

13986
if sys.version_info >= (3, 3):

cherrypy/_cperror.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -119,13 +119,11 @@ class Root:
119119

120120
import io
121121
import contextlib
122+
import urllib.parse
122123
from sys import exc_info as _exc_info
123124
from traceback import format_exception as _format_exception
124125
from xml.sax import saxutils
125126

126-
import six
127-
from six.moves import urllib
128-
129127
from more_itertools import always_iterable
130128

131129
import cherrypy
@@ -496,7 +494,7 @@ def get_error_page(status, **kwargs):
496494
if kwargs.get('version') is None:
497495
kwargs['version'] = cherrypy.__version__
498496

499-
for k, v in six.iteritems(kwargs):
497+
for k, v in kwargs.items():
500498
if v is None:
501499
kwargs[k] = ''
502500
else:
@@ -520,13 +518,13 @@ def get_error_page(status, **kwargs):
520518
if cherrypy.lib.is_iterator(result):
521519
from cherrypy.lib.encoding import UTF8StreamEncoder
522520
return UTF8StreamEncoder(result)
523-
elif isinstance(result, six.text_type):
521+
elif isinstance(result, str):
524522
return result.encode('utf-8')
525523
else:
526524
if not isinstance(result, bytes):
527525
raise ValueError(
528526
'error page function did not '
529-
'return a bytestring, six.text_type or an '
527+
'return a bytestring, str or an '
530528
'iterator - returned object of type %s.'
531529
% (type(result).__name__))
532530
return result

cherrypy/_cplogging.py

Lines changed: 3 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,6 @@
113113
import os
114114
import sys
115115

116-
import six
117-
118116
import cherrypy
119117
from cherrypy import _cperror
120118

@@ -155,11 +153,7 @@ class LogManager(object):
155153
access_log = None
156154
"""The actual :class:`logging.Logger` instance for access messages."""
157155

158-
access_log_format = (
159-
'{h} {l} {u} {t} "{r}" {s} {b} "{f}" "{a}"'
160-
if six.PY3 else
161-
'%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'
162-
)
156+
access_log_format = '{h} {l} {u} {t} "{r}" {s} {b} "{f}" "{a}"'
163157

164158
logger_root = None
165159
"""The "top-level" logger name.
@@ -254,8 +248,7 @@ def access(self):
254248
status = '-'
255249
else:
256250
status = response.output_status.split(b' ', 1)[0]
257-
if six.PY3:
258-
status = status.decode('ISO-8859-1')
251+
status = status.decode('ISO-8859-1')
259252

260253
atoms = {'h': remote.name or remote.ip,
261254
'l': '-',
@@ -270,7 +263,7 @@ def access(self):
270263
'i': request.unique_id,
271264
'z': LazyRfc3339UtcTime(),
272265
}
273-
if six.PY3:
266+
if True:
274267
for k, v in atoms.items():
275268
if not isinstance(v, str):
276269
v = str(v)
@@ -292,23 +285,6 @@ def access(self):
292285
logging.INFO, self.access_log_format.format(**atoms))
293286
except Exception:
294287
self(traceback=True)
295-
else:
296-
for k, v in atoms.items():
297-
if isinstance(v, six.text_type):
298-
v = v.encode('utf8')
299-
elif not isinstance(v, str):
300-
v = str(v)
301-
# Fortunately, repr(str) escapes unprintable chars, \n, \t, etc
302-
# and backslash for us. All we have to do is strip the quotes.
303-
v = repr(v)[1:-1]
304-
# Escape double-quote.
305-
atoms[k] = v.replace('"', '\\"')
306-
307-
try:
308-
self.access_log.log(
309-
logging.INFO, self.access_log_format % atoms)
310-
except Exception:
311-
self(traceback=True)
312288

313289
def time(self):
314290
"""Return now() in Apache Common Log Format (no timezone)."""

cherrypy/_cpmodpy.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,6 @@ def setup_server():
6161
import re
6262
import sys
6363

64-
import six
65-
6664
from more_itertools import always_iterable
6765

6866
import cherrypy
@@ -197,7 +195,7 @@ def handler(req):
197195
path = req.uri
198196
qs = req.args or ''
199197
reqproto = req.protocol
200-
headers = list(six.iteritems(req.headers_in))
198+
headers = list(req.headers_in.items())
201199
rfile = _ReadOnlyRequest(req)
202200
prev = None
203201

cherrypy/_cpreqbody.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,6 @@ def unquote_plus(bs):
131131
pass
132132
return b''.join(atoms)
133133

134-
import six
135134
import cheroot.server
136135

137136
import cherrypy
@@ -986,12 +985,6 @@ def process(self):
986985
# add them in here.
987986
request_params = self.request_params
988987
for key, value in self.params.items():
989-
# Python 2 only: keyword arguments must be byte strings (type
990-
# 'str').
991-
if sys.version_info < (3, 0):
992-
if isinstance(key, six.text_type):
993-
key = key.encode('ISO-8859-1')
994-
995988
if key in request_params:
996989
if not isinstance(request_params[key], list):
997990
request_params[key] = [request_params[key]]

cherrypy/_cprequest.py

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
import sys
22
import time
3+
from http.cookies import SimpleCookie, CookieError
34

45
import uuid
56

6-
import six
7-
from six.moves.http_cookies import SimpleCookie, CookieError
8-
97
from more_itertools import consume
108

119
import cherrypy
@@ -141,7 +139,7 @@ def hooks_namespace(k, v):
141139
# hookpoint per path (e.g. "hooks.before_handler.1").
142140
# Little-known fact you only get from reading source ;)
143141
hookpoint = k.split('.', 1)[0]
144-
if isinstance(v, six.string_types):
142+
if isinstance(v, str):
145143
v = cherrypy.lib.reprconf.attributes(v)
146144
if not isinstance(v, Hook):
147145
v = Hook(v)
@@ -704,12 +702,6 @@ def process_query_string(self):
704702
'strings for this resource must be encoded with %r.' %
705703
self.query_string_encoding)
706704

707-
# Python 2 only: keyword arguments must be byte strings (type 'str').
708-
if six.PY2:
709-
for key, value in p.items():
710-
if isinstance(key, six.text_type):
711-
del p[key]
712-
p[key.encode(self.query_string_encoding)] = value
713705
self.params.update(p)
714706

715707
def process_headers(self):
@@ -786,11 +778,11 @@ def __get__(self, obj, objclass=None):
786778

787779
def __set__(self, obj, value):
788780
# Convert the given value to an iterable object.
789-
if isinstance(value, six.text_type):
781+
if isinstance(value, str):
790782
raise ValueError(self.unicode_err)
791783
elif isinstance(value, list):
792784
# every item in a list must be bytes...
793-
if any(isinstance(item, six.text_type) for item in value):
785+
if any(isinstance(item, str) for item in value):
794786
raise ValueError(self.unicode_err)
795787

796788
obj._body = encoding.prepare_iter(value)
@@ -903,9 +895,9 @@ def finalize(self):
903895
if cookie:
904896
for line in cookie.split('\r\n'):
905897
name, value = line.split(': ', 1)
906-
if isinstance(name, six.text_type):
898+
if isinstance(name, str):
907899
name = name.encode('ISO-8859-1')
908-
if isinstance(value, six.text_type):
900+
if isinstance(value, str):
909901
value = headers.encode(value)
910902
h.append((name, value))
911903

cherrypy/_cpserver.py

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
"""Manage HTTP servers with CherryPy."""
22

3-
import six
4-
53
import cherrypy
64
from cherrypy.lib.reprconf import attributes
75
from cherrypy._cpcompat import text_or_bytes
@@ -116,21 +114,13 @@ def socket_host(self, value):
116114
ssl_ciphers = None
117115
"""The ciphers list of SSL."""
118116

119-
if six.PY3:
117+
if True:
120118
ssl_module = 'builtin'
121119
"""The name of a registered SSL adaptation module to use with
122120
the builtin WSGI server. Builtin options are: 'builtin' (to
123121
use the SSL library built into recent versions of Python).
124122
You may also register your own classes in the
125123
cheroot.server.ssl_adapters dict."""
126-
else:
127-
ssl_module = 'pyopenssl'
128-
"""The name of a registered SSL adaptation module to use with the
129-
builtin WSGI server. Builtin options are 'builtin' (to use the SSL
130-
library built into recent versions of Python) and 'pyopenssl' (to
131-
use the PyOpenSSL project, which you must install separately). You
132-
may also register your own classes in the cheroot.server.ssl_adapters
133-
dict."""
134124

135125
statistics = False
136126
"""Turns statistics-gathering on or off for aware HTTP servers."""

0 commit comments

Comments
 (0)