Permalink
Browse files

Refs #23919 -- Removed six.PY2/PY3 usage

Thanks Tim Graham for the review.
  • Loading branch information...
claudep committed Dec 1, 2016
1 parent e63d98b commit c716fe87821df00f9f03ecc761c914d1682591a2
Showing with 308 additions and 1,299 deletions.
  1. +1 −7 django/contrib/admindocs/views.py
  2. +0 −8 django/contrib/auth/management/__init__.py
  3. +2 −4 django/contrib/auth/migrations/0001_initial.py
  4. +1 −2 django/contrib/auth/migrations/0004_alter_user_username_opts.py
  5. +1 −2 django/contrib/auth/migrations/0007_alter_validators_add_error_messages.py
  6. +1 −2 django/contrib/auth/migrations/0008_alter_user_username_max_length.py
  7. +2 −2 django/contrib/auth/models.py
  8. +2 −3 django/contrib/auth/validators.py
  9. +1 −2 django/contrib/gis/utils/ogrinspect.py
  10. +1 −6 django/contrib/postgres/signals.py
  11. +2 −4 django/core/cache/backends/db.py
  12. +1 −5 django/core/exceptions.py
  13. +2 −6 django/core/files/base.py
  14. +7 −10 django/core/handlers/wsgi.py
  15. +2 −4 django/core/mail/backends/console.py
  16. +15 −31 django/core/mail/message.py
  17. +1 −2 django/core/management/commands/loaddata.py
  18. +2 −4 django/core/management/commands/runserver.py
  19. +6 −16 django/core/management/templates.py
  20. +0 −2 django/db/backends/mysql/base.py
  21. +0 −2 django/db/backends/oracle/operations.py
  22. +0 −4 django/db/backends/postgresql/base.py
  23. +0 −4 django/db/backends/sqlite3/base.py
  24. +0 −2 django/db/backends/sqlite3/features.py
  25. +2 −8 django/db/migrations/questioner.py
  26. +2 −10 django/db/migrations/serializer.py
  27. +1 −3 django/db/models/base.py
  28. +2 −7 django/db/models/fields/related.py
  29. +1 −4 django/db/models/manager.py
  30. +1 −1 django/db/utils.py
  31. +3 −12 django/dispatch/dispatcher.py
  32. +0 −67 django/dispatch/weakref_backports.py
  33. +1 −31 django/http/cookie.py
  34. +2 −7 django/http/multipartparser.py
  35. +10 −19 django/http/request.py
  36. +7 −21 django/http/response.py
  37. +4 −6 django/test/client.py
  38. +2 −2 django/test/signals.py
  39. +0 −6 django/test/testcases.py
  40. +2 −7 django/test/utils.py
  41. +1 −5 django/urls/resolvers.py
  42. +2 −27 django/utils/_os.py
  43. +1 −2 django/utils/crypto.py
  44. +3 −21 django/utils/datastructures.py
  45. +2 −7 django/utils/decorators.py
  46. +9 −26 django/utils/encoding.py
  47. +1 −5 django/utils/feedgenerator.py
  48. +6 −20 django/utils/functional.py
  49. +0 −19 django/utils/glob.py
  50. +8 −18 django/utils/html.py
  51. +9 −12 django/utils/html_parser.py
  52. +5 −24 django/utils/http.py
  53. +2 −46 django/utils/inspect.py
  54. +12 −82 django/utils/module_loading.py
  55. +1 −6 django/utils/safestring.py
  56. +0 −5 django/utils/text.py
  57. +1 −2 django/utils/translation/template.py
  58. +3 −15 django/utils/translation/trans_real.py
  59. +3 −7 django/views/debug.py
  60. +1 −1 setup.cfg
  61. +1 −3 tests/admin_docs/test_views.py
  62. +6 −14 tests/admin_scripts/tests.py
  63. +1 −2 tests/annotations/tests.py
  64. +0 −3 tests/apps/tests.py
  65. +4 −10 tests/auth_tests/test_forms.py
  66. +0 −3 tests/auth_tests/test_management.py
  67. +0 −14 tests/auth_tests/test_tokens.py
  68. +2 −3 tests/backends/test_utils.py
  69. +0 −9 tests/base/models.py
  70. +1 −5 tests/cache/tests.py
  71. +6 −11 tests/dbshell/test_postgresql_psycopg2.py
  72. +2 −4 tests/file_uploads/tests.py
  73. +1 −4 tests/files/tests.py
  74. +3 −18 tests/fixtures_regress/tests.py
  75. +6 −14 tests/handlers/tests.py
  76. +0 −34 tests/httpwrappers/tests.py
  77. +6 −13 tests/i18n/test_compilation.py
  78. +4 −48 tests/i18n/tests.py
  79. +2 −6 tests/inspectdb/tests.py
  80. +3 −7 tests/invalid_models_tests/test_relative_fields.py
  81. +9 −34 tests/mail/tests.py
  82. +0 −19 tests/middleware/tests.py
  83. +4 −12 tests/migrations/test_commands.py
  84. +0 −4 tests/migrations/test_loader.py
  85. +0 −15 tests/migrations/test_writer.py
  86. +5 −11 tests/model_fields/test_promises.py
  87. +0 −7 tests/project_template/test_settings.py
  88. +1 −23 tests/queries/tests.py
  89. +1 −4 tests/queryset_pickle/models.py
  90. +0 −3 tests/queryset_pickle/tests.py
  91. +3 −5 tests/requests/tests.py
  92. +0 −5 tests/signing/tests.py
  93. +1 −2 tests/staticfiles_tests/test_management.py
  94. +6 −21 tests/str/models.py
  95. +1 −12 tests/str/tests.py
  96. +2 −4 tests/template_tests/syntax_tests/test_width_ratio.py
  97. +0 −3 tests/template_tests/test_custom.py
  98. +0 −2 tests/template_tests/test_loaders.py
  99. +2 −5 tests/template_tests/test_nodelist.py
  100. +0 −3 tests/test_runner/test_debug_sql.py
  101. +1 −5 tests/test_runner/test_parallel.py
  102. +1 −8 tests/urlpatterns_reverse/tests.py
  103. +9 −22 tests/utils_tests/test_encoding.py
  104. +5 −12 tests/utils_tests/test_functional.py
  105. +0 −13 tests/utils_tests/test_glob.py
  106. +15 −35 tests/utils_tests/test_html.py
  107. +1 −17 tests/utils_tests/test_http.py
  108. +0 −7 tests/utils_tests/test_simplelazyobject.py
  109. +0 −45 tests/view_tests/tests/py3_test_debug.py
  110. +32 −16 tests/view_tests/tests/test_debug.py
  111. +1 −5 tests/view_tests/tests/test_i18n.py
@@ -15,7 +15,6 @@
from django.http import Http404
from django.template.engine import Engine
from django.urls import get_mod_func, get_resolver, get_urlconf, reverse
-from django.utils import six
from django.utils.decorators import method_decorator
from django.utils.inspect import (
func_accepts_kwargs, func_accepts_var_args, func_has_no_args,
@@ -132,12 +131,7 @@ class ViewIndexView(BaseAdminDocsView):
@staticmethod
def _get_full_name(func):
mod_name = func.__module__
- if six.PY3:
- return '%s.%s' % (mod_name, func.__qualname__)
- else:
- # PY2 does not support __qualname__
- func_name = getattr(func, '__name__', func.__class__.__name__)
- return '%s.%s' % (mod_name, func_name)
+ return '%s.%s' % (mod_name, func.__qualname__)
def get_context_data(self, **kwargs):
views = []
@@ -8,8 +8,6 @@
from django.contrib.auth import get_permission_codename
from django.core import exceptions
from django.db import DEFAULT_DB_ALIAS, router
-from django.utils import six
-from django.utils.encoding import DEFAULT_LOCALE_ENCODING
def _get_all_permissions(opts):
@@ -98,12 +96,6 @@ def get_system_username():
# if there is no corresponding entry in the /etc/passwd file
# (a very restricted chroot environment, for example).
return ''
- if six.PY2:
- try:
- result = result.decode(DEFAULT_LOCALE_ENCODING)
- except UnicodeDecodeError:
- # UnicodeDecodeError - preventive treatment for non-latin Windows.
- return ''
return result
@@ -1,7 +1,7 @@
import django.contrib.auth.models
from django.contrib.auth import validators
from django.db import migrations, models
-from django.utils import six, timezone
+from django.utils import timezone
class Migration(migrations.Migration):
@@ -63,9 +63,7 @@ class Migration(migrations.Migration):
('username', models.CharField(
help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', unique=True,
max_length=30, verbose_name='username',
- validators=[
- validators.UnicodeUsernameValidator() if six.PY3 else validators.ASCIIUsernameValidator()
- ],
+ validators=[validators.UnicodeUsernameValidator()],
)),
('first_name', models.CharField(max_length=30, verbose_name='first name', blank=True)),
('last_name', models.CharField(max_length=30, verbose_name='last name', blank=True)),
@@ -1,6 +1,5 @@
from django.contrib.auth import validators
from django.db import migrations, models
-from django.utils import six
class Migration(migrations.Migration):
@@ -16,7 +15,7 @@ class Migration(migrations.Migration):
name='username',
field=models.CharField(
error_messages={'unique': 'A user with that username already exists.'}, max_length=30,
- validators=[validators.UnicodeUsernameValidator() if six.PY3 else validators.ASCIIUsernameValidator()],
+ validators=[validators.UnicodeUsernameValidator()],
help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.',
unique=True, verbose_name='username'
),
@@ -1,6 +1,5 @@
from django.contrib.auth import validators
from django.db import migrations, models
-from django.utils import six
class Migration(migrations.Migration):
@@ -18,7 +17,7 @@ class Migration(migrations.Migration):
help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.',
max_length=30,
unique=True,
- validators=[validators.UnicodeUsernameValidator() if six.PY3 else validators.ASCIIUsernameValidator()],
+ validators=[validators.UnicodeUsernameValidator()],
verbose_name='username',
),
),
@@ -1,6 +1,5 @@
from django.contrib.auth import validators
from django.db import migrations, models
-from django.utils import six
class Migration(migrations.Migration):
@@ -18,7 +17,7 @@ class Migration(migrations.Migration):
help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.',
max_length=150,
unique=True,
- validators=[validators.UnicodeUsernameValidator() if six.PY3 else validators.ASCIIUsernameValidator()],
+ validators=[validators.UnicodeUsernameValidator()],
verbose_name='username',
),
),
@@ -9,7 +9,7 @@
from django.utils import six, timezone
from django.utils.translation import ugettext_lazy as _
-from .validators import ASCIIUsernameValidator, UnicodeUsernameValidator
+from .validators import UnicodeUsernameValidator
def update_last_login(sender, user, **kwargs):
@@ -297,7 +297,7 @@ class AbstractUser(AbstractBaseUser, PermissionsMixin):
Username and password are required. Other fields are optional.
"""
- username_validator = UnicodeUsernameValidator() if six.PY3 else ASCIIUsernameValidator()
+ username_validator = UnicodeUsernameValidator()
username = models.CharField(
_('username'),
@@ -1,7 +1,6 @@
import re
from django.core import validators
-from django.utils import six
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _
@@ -13,7 +12,7 @@ class ASCIIUsernameValidator(validators.RegexValidator):
'Enter a valid username. This value may contain only English letters, '
'numbers, and @/./+/-/_ characters.'
)
- flags = re.ASCII if six.PY3 else 0
+ flags = re.ASCII
@deconstructible
@@ -23,4 +22,4 @@ class UnicodeUsernameValidator(validators.RegexValidator):
'Enter a valid username. This value may contain only letters, '
'numbers, and @/./+/-/_ characters.'
)
- flags = re.UNICODE if six.PY2 else 0
+ flags = 0
@@ -235,5 +235,4 @@ def get_kwargs_str(field_name):
if name_field:
yield ''
- yield ' def __%s__(self): return self.%s' % (
- 'str' if six.PY3 else 'unicode', name_field)
+ yield ' def __str__(self): return self.%s' % name_field
@@ -1,18 +1,13 @@
from psycopg2 import ProgrammingError
from psycopg2.extras import register_hstore
-from django.utils import six
-
def register_hstore_handler(connection, **kwargs):
if connection.vendor != 'postgresql':
return
try:
- if six.PY2:
- register_hstore(connection.connection, globally=True, unicode=True)
- else:
- register_hstore(connection.connection, globally=True)
+ register_hstore(connection.connection, globally=True)
except ProgrammingError:
# Hstore is not available on the database.
#
@@ -5,7 +5,7 @@
from django.conf import settings
from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache
from django.db import DatabaseError, connections, models, router, transaction
-from django.utils import six, timezone
+from django.utils import timezone
from django.utils.encoding import force_bytes
try:
@@ -112,11 +112,9 @@ def _base_set(self, mode, key, value, timeout=DEFAULT_TIMEOUT):
if num > self._max_entries:
self._cull(db, cursor, now)
pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL)
- b64encoded = base64.b64encode(pickled)
# The DB column is expecting a string, so make sure the value is a
# string, not bytes. Refs #19274.
- if six.PY3:
- b64encoded = b64encoded.decode('latin1')
+ b64encoded = base64.b64encode(pickled).decode('latin1')
try:
# Note: typecasting for datetimes is needed by some 3rd party
# database backends. All core backends work without typecasting,
@@ -1,7 +1,6 @@
"""
Global Django exception and warning classes.
"""
-from django.utils import six
from django.utils.encoding import force_text
@@ -115,10 +114,7 @@ def __init__(self, message, code=None, params=None):
if isinstance(message, ValidationError):
if hasattr(message, 'error_dict'):
message = message.error_dict
- # PY2 has a `message` property which is always there so we can't
- # duck-type on it. It was introduced in Python 2.5 and already
- # deprecated in Python 2.6.
- elif not hasattr(message, 'message' if six.PY3 else 'code'):
+ elif not hasattr(message, 'message'):
message = message.error_list
else:
message, code, params = message.message, message.code, message.params
@@ -3,7 +3,7 @@
from django.core.files.utils import FileProxyMixin
from django.utils import six
-from django.utils.encoding import force_bytes, force_str, force_text
+from django.utils.encoding import force_str, force_text
class File(FileProxyMixin):
@@ -140,11 +140,7 @@ class ContentFile(File):
A File-like object that takes just raw content, rather than an actual file.
"""
def __init__(self, content, name=None):
- if six.PY3:
- stream_class = StringIO if isinstance(content, six.text_type) else BytesIO
- else:
- stream_class = BytesIO
- content = force_bytes(content)
+ stream_class = StringIO if isinstance(content, six.text_type) else BytesIO
super(ContentFile, self).__init__(stream_class(content), name=name)
self.size = len(content)
@@ -8,7 +8,6 @@
from django.core import signals
from django.core.handlers import base
from django.urls import set_script_prefix
-from django.utils import six
from django.utils.encoding import (
force_str, force_text, repercent_broken_unicode,
)
@@ -212,22 +211,20 @@ def get_bytes_from_wsgi(environ, key, default):
"""
Get a value from the WSGI environ dictionary as bytes.
- key and default should be str objects. Under Python 2 they may also be
- unicode objects provided they only contain ASCII characters.
+ key and default should be str objects.
"""
value = environ.get(str(key), str(default))
- # Under Python 3, non-ASCII values in the WSGI environ are arbitrarily
- # decoded with ISO-8859-1. This is wrong for Django websites where UTF-8
- # is the default. Re-encode to recover the original bytestring.
- return value.encode(ISO_8859_1) if six.PY3 else value
+ # Non-ASCII values in the WSGI environ are arbitrarily decoded with
+ # ISO-8859-1. This is wrong for Django websites where UTF-8 is the default.
+ # Re-encode to recover the original bytestring.
+ return value.encode(ISO_8859_1)
def get_str_from_wsgi(environ, key, default):
"""
Get a value from the WSGI environ dictionary as str.
- key and default should be str objects. Under Python 2 they may also be
- unicode objects provided they only contain ASCII characters.
+ key and default should be str objects.
"""
value = get_bytes_from_wsgi(environ, key, default)
- return value.decode(UTF_8, errors='replace') if six.PY3 else value
+ return value.decode(UTF_8, errors='replace')
@@ -5,7 +5,6 @@
import threading
from django.core.mail.backends.base import BaseEmailBackend
-from django.utils import six
class EmailBackend(BaseEmailBackend):
@@ -17,9 +16,8 @@ def __init__(self, *args, **kwargs):
def write_message(self, message):
msg = message.message()
msg_data = msg.as_bytes()
- if six.PY3:
- charset = msg.get_charset().get_output_charset() if msg.get_charset() else 'utf-8'
- msg_data = msg_data.decode(charset)
+ charset = msg.get_charset().get_output_charset() if msg.get_charset() else 'utf-8'
+ msg_data = msg_data.decode(charset)
self.stream.write('%s\n' % msg_data)
self.stream.write('-' * 79)
self.stream.write('\n')
@@ -5,7 +5,9 @@
from email import (
charset as Charset, encoders as Encoders, generator, message_from_string,
)
+from email.errors import InvalidHeaderDefect, NonASCIILocalPartDefect
from email.header import Header
+from email.headerregistry import Address
from email.message import Message
from email.mime.base import MIMEBase
from email.mime.message import MIMEMessage
@@ -139,18 +141,8 @@ def sanitize_address(addr, encoding):
except UnicodeEncodeError: # IDN or non-ascii in the local part
localpart, domain = split_addr(addr, encoding)
- if six.PY2:
- # On Python 2, use the stdlib since `email.headerregistry` doesn't exist.
- from email.utils import formataddr
- if localpart and domain:
- addr = '@'.join([localpart, domain])
- return formataddr((nm, addr))
-
- # On Python 3, an `email.headerregistry.Address` object is used since
+ # An `email.headerregistry.Address` object is used since
# email.utils.formataddr() naively encodes the name as ascii (see #25986).
- from email.headerregistry import Address
- from email.errors import InvalidHeaderDefect, NonASCIILocalPartDefect
-
if localpart and domain:
address = Address(nm, username=localpart, domain=domain)
return str(address)
@@ -174,27 +166,21 @@ def as_string(self, unixfrom=False, linesep='\n'):
"""
fp = six.StringIO()
g = generator.Generator(fp, mangle_from_=False)
- if six.PY2:
- g.flatten(self, unixfrom=unixfrom)
- else:
- g.flatten(self, unixfrom=unixfrom, linesep=linesep)
+ g.flatten(self, unixfrom=unixfrom, linesep=linesep)
return fp.getvalue()
- if six.PY2:
- as_bytes = as_string
- else:
- def as_bytes(self, unixfrom=False, linesep='\n'):
- """Return the entire formatted message as bytes.
- Optional `unixfrom' when True, means include the Unix From_ envelope
- header.
+ def as_bytes(self, unixfrom=False, linesep='\n'):
+ """Return the entire formatted message as bytes.
+ Optional `unixfrom' when True, means include the Unix From_ envelope
+ header.
- This overrides the default as_bytes() implementation to not mangle
- lines that begin with 'From '. See bug #13433 for details.
- """
- fp = BytesIO()
- g = generator.BytesGenerator(fp, mangle_from_=False)
- g.flatten(self, unixfrom=unixfrom, linesep=linesep)
- return fp.getvalue()
+ This overrides the default as_bytes() implementation to not mangle
+ lines that begin with 'From '. See bug #13433 for details.
+ """
+ fp = BytesIO()
+ g = generator.BytesGenerator(fp, mangle_from_=False)
+ g.flatten(self, unixfrom=unixfrom, linesep=linesep)
+ return fp.getvalue()
class SafeMIMEMessage(MIMEMixin, MIMEMessage):
@@ -450,8 +436,6 @@ def _create_attachment(self, filename, content, mimetype=None):
try:
filename.encode('ascii')
except UnicodeEncodeError:
- if six.PY2:
- filename = filename.encode('utf-8')
filename = ('utf-8', '', filename)
attachment.add_header('Content-Disposition', 'attachment',
filename=filename)
@@ -20,7 +20,6 @@
from django.utils._os import upath
from django.utils.encoding import force_text
from django.utils.functional import cached_property
-from django.utils.glob import glob_escape
try:
import bz2
@@ -238,7 +237,7 @@ def find_fixtures(self, fixture_label):
self.stdout.write("Checking %s for fixtures..." % humanize(fixture_dir))
fixture_files_in_dir = []
path = os.path.join(fixture_dir, fixture_name)
- for candidate in glob.iglob(glob_escape(path) + '*'):
+ for candidate in glob.iglob(glob.escape(path) + '*'):
if os.path.basename(candidate) in targets:
# Save the fixture_dir and fixture_name for future error messages.
fixture_files_in_dir.append((candidate, fixture_dir, fixture_name))
Oops, something went wrong.

0 comments on commit c716fe8

Please sign in to comment.