Permalink
Browse files

Refs #23919 -- Removed unneeded force_str calls

  • Loading branch information...
claudep committed Jan 11, 2017
1 parent bf1c957 commit dc8834cad41aa407f402dc54788df3cd37ab3e22
Showing with 100 additions and 167 deletions.
  1. +2 −5 django/contrib/admin/utils.py
  2. +3 −3 django/contrib/auth/hashers.py
  3. +1 −2 django/contrib/auth/management/commands/changepassword.py
  4. +5 −6 django/contrib/auth/management/commands/createsuperuser.py
  5. +0 −5 django/core/cache/backends/memcached.py
  6. +2 −2 django/core/checks/messages.py
  7. +2 −2 django/core/files/base.py
  8. +1 −3 django/core/files/uploadedfile.py
  9. +3 −6 django/core/handlers/wsgi.py
  10. +1 −2 django/core/mail/backends/smtp.py
  11. +5 −5 django/core/management/base.py
  12. +3 −3 django/core/management/commands/makemessages.py
  13. +6 −11 django/core/signing.py
  14. +1 −2 django/db/backends/mysql/base.py
  15. +1 −2 django/db/backends/postgresql/base.py
  16. +2 −2 django/db/models/base.py
  17. +2 −2 django/db/models/fields/files.py
  18. +4 −4 django/forms/fields.py
  19. +2 −2 django/forms/widgets.py
  20. +3 −7 django/http/request.py
  21. +1 −4 django/http/response.py
  22. +2 −3 django/template/base.py
  23. +5 −5 django/test/client.py
  24. +1 −2 django/test/utils.py
  25. +2 −2 django/urls/resolvers.py
  26. +3 −5 django/utils/formats.py
  27. +3 −3 django/utils/html.py
  28. +3 −3 django/utils/tree.py
  29. +2 −2 django/views/debug.py
  30. +2 −2 django/views/generic/dates.py
  31. +1 −1 tests/admin_scripts/tests.py
  32. +1 −5 tests/admin_utils/tests.py
  33. +1 −2 tests/auth_tests/test_management.py
  34. +2 −2 tests/contenttypes_tests/tests.py
  35. +10 −20 tests/dbshell/test_postgresql_psycopg2.py
  36. +2 −4 tests/file_uploads/views.py
  37. +1 −2 tests/generic_views/test_list.py
  38. +1 −5 tests/handlers/tests.py
  39. +2 −8 tests/httpwrappers/tests.py
  40. +1 −2 tests/middleware/tests.py
  41. +1 −2 tests/migrations/test_writer.py
  42. +2 −3 tests/or_lookups/tests.py
  43. +1 −2 tests/requests/tests.py
  44. +1 −2 tests/signing/tests.py
@@ -11,7 +11,7 @@
from django.forms.utils import pretty_name
from django.urls import NoReverseMatch, reverse
from django.utils import formats, timezone
-from django.utils.encoding import force_str, force_text, smart_text
+from django.utils.encoding import force_text, smart_text
from django.utils.html import format_html
from django.utils.text import capfirst
from django.utils.translation import (
@@ -340,12 +340,9 @@ def label_for_field(name, model, model_admin=None, return_attr=False):
# field is likely a ForeignObjectRel
label = field.related_model._meta.verbose_name
except FieldDoesNotExist:
- if name == "__unicode__":
+ if name == "__str__":
label = force_text(model._meta.verbose_name)
attr = str
- elif name == "__str__":
- label = force_str(model._meta.verbose_name)
- attr = bytes
else:
if callable(name):
attr = name
@@ -13,7 +13,7 @@
from django.utils.crypto import (
constant_time_compare, get_random_string, pbkdf2,
)
-from django.utils.encoding import force_bytes, force_str, force_text
+from django.utils.encoding import force_bytes, force_text
from django.utils.module_loading import import_string
from django.utils.translation import ugettext_noop as _
@@ -627,7 +627,7 @@ def salt(self):
def encode(self, password, salt):
crypt = self._load_library()
assert len(salt) == 2
- data = crypt.crypt(force_str(password), salt)
+ data = crypt.crypt(password, salt)
assert data is not None # A platform like OpenBSD with a dummy crypt module.
# we don't need to store the salt, but Django used to do this
return "%s$%s$%s" % (self.algorithm, '', data)
@@ -636,7 +636,7 @@ def verify(self, password, encoded):
crypt = self._load_library()
algorithm, salt, data = encoded.split('$', 2)
assert algorithm == self.algorithm
- return constant_time_compare(data, crypt.crypt(force_str(password), data))
+ return constant_time_compare(data, crypt.crypt(password, data))
def safe_summary(self, encoded):
algorithm, salt, data = encoded.split('$', 2)
@@ -5,7 +5,6 @@
from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS
-from django.utils.encoding import force_str
UserModel = get_user_model()
@@ -16,7 +15,7 @@ class Command(BaseCommand):
requires_system_checks = False
def _get_pass(self, prompt="Password: "):
- p = getpass.getpass(prompt=force_str(prompt))
+ p = getpass.getpass(prompt=prompt)
if not p:
raise CommandError("aborted")
return p
@@ -10,7 +10,6 @@
from django.core import exceptions
from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS
-from django.utils.encoding import force_str
from django.utils.text import capfirst
@@ -103,12 +102,12 @@ def handle(self, *args, **options):
if default_username:
input_msg += " (leave blank to use '%s')" % default_username
username_rel = self.username_field.remote_field
- input_msg = force_str('%s%s: ' % (
+ input_msg = '%s%s: ' % (
input_msg,
' (%s.%s)' % (
username_rel.model._meta.object_name,
username_rel.field_name
- ) if username_rel else '')
+ ) if username_rel else ''
)
username = self.get_input_data(self.username_field, input_msg, default_username)
if not username:
@@ -126,13 +125,13 @@ def handle(self, *args, **options):
field = self.UserModel._meta.get_field(field_name)
user_data[field_name] = options[field_name]
while user_data[field_name] is None:
- message = force_str('%s%s: ' % (
+ message = '%s%s: ' % (
capfirst(field.verbose_name),
' (%s.%s)' % (
field.remote_field.model._meta.object_name,
field.remote_field.field_name,
) if field.remote_field else '',
- ))
+ )
input_value = self.get_input_data(field, message)
user_data[field_name] = input_value
fake_user_data[field_name] = input_value
@@ -144,7 +143,7 @@ def handle(self, *args, **options):
# Get a password
while password is None:
password = getpass.getpass()
- password2 = getpass.getpass(force_str('Password (again): '))
+ password2 = getpass.getpass('Password (again): ')
if password != password2:
self.stderr.write("Error: Your passwords didn't match.")
password = None
@@ -7,7 +7,6 @@
from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache
from django.utils.deprecation import RemovedInDjango21Warning
-from django.utils.encoding import force_str
from django.utils.functional import cached_property
@@ -65,10 +64,6 @@ def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT):
timeout += int(time.time())
return int(timeout)
- def make_key(self, key, version=None):
- # Python 2 memcache requires the key to be a byte string.
- return force_str(super(BaseMemcachedCache, self).make_key(key, version))
-
def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
key = self.make_key(key, version=version)
return self._cache.add(key, value, self.get_backend_timeout(timeout))
@@ -1,4 +1,4 @@
-from django.utils.encoding import force_str
+from django.utils.encoding import force_text
# Levels
DEBUG = 10
@@ -35,7 +35,7 @@ def __str__(self):
# method doesn't return "applabel.modellabel" and cannot be changed.
obj = self.obj._meta.label
else:
- obj = force_str(self.obj)
+ obj = force_text(self.obj)
id = "(%s) " % self.id if self.id else ""
hint = "\n\tHINT: %s" % self.hint if self.hint else ''
return "%s: %s%s%s" % (obj, id, self.msg, hint)
@@ -2,7 +2,7 @@
from io import BytesIO, StringIO, UnsupportedOperation
from django.core.files.utils import FileProxyMixin
-from django.utils.encoding import force_str, force_text
+from django.utils.encoding import force_text
class File(FileProxyMixin):
@@ -20,7 +20,7 @@ def __str__(self):
return force_text(self.name or '')
def __repr__(self):
- return force_str("<%s: %s>" % (self.__class__.__name__, self or "None"))
+ return "<%s: %s>" % (self.__class__.__name__, self or "None")
def __bool__(self):
return bool(self.name)
@@ -9,7 +9,6 @@
from django.conf import settings
from django.core.files import temp as tempfile
from django.core.files.base import File
-from django.utils.encoding import force_str
__all__ = ('UploadedFile', 'TemporaryUploadedFile', 'InMemoryUploadedFile',
'SimpleUploadedFile')
@@ -33,8 +32,7 @@ def __init__(self, file=None, name=None, content_type=None, size=None, charset=N
self.content_type_extra = content_type_extra
def __repr__(self):
- return force_str("<%s: %s (%s)>" % (
- self.__class__.__name__, self.name, self.content_type))
+ return "<%s: %s (%s)>" % (self.__class__.__name__, self.name, self.content_type)
def _get_name(self):
return self._name
@@ -8,13 +8,10 @@
from django.core import signals
from django.core.handlers import base
from django.urls import set_script_prefix
-from django.utils.encoding import (
- force_str, force_text, repercent_broken_unicode,
-)
+from django.utils.encoding import force_text, repercent_broken_unicode
from django.utils.functional import cached_property
-# encode() and decode() expect the charset to be a native string.
-ISO_8859_1, UTF_8 = str('iso-8859-1'), str('utf-8')
+ISO_8859_1, UTF_8 = 'iso-8859-1', 'utf-8'
_slashes_re = re.compile(br'/+')
@@ -159,7 +156,7 @@ def __call__(self, environ, start_response):
response_headers = [(str(k), str(v)) for k, v in response.items()]
for c in response.cookies.values():
response_headers.append((str('Set-Cookie'), str(c.output(header=''))))
- start_response(force_str(status), response_headers)
+ start_response(status, response_headers)
if getattr(response, 'file_to_stream', None) is not None and environ.get('wsgi.file_wrapper'):
response = environ['wsgi.file_wrapper'](response.file_to_stream)
return response
@@ -8,7 +8,6 @@
from django.core.mail.backends.base import BaseEmailBackend
from django.core.mail.message import sanitize_address
from django.core.mail.utils import DNS_NAME
-from django.utils.encoding import force_str
class EmailBackend(BaseEmailBackend):
@@ -68,7 +67,7 @@ def open(self):
if not self.use_ssl and self.use_tls:
self.connection.starttls(keyfile=self.ssl_keyfile, certfile=self.ssl_certfile)
if self.username and self.password:
- self.connection.login(force_str(self.username), force_str(self.password))
+ self.connection.login(self.username, self.password)

This comment has been minimized.

Show comment
Hide comment
@emg36

emg36 Jan 31, 2017

Why was this changed? I have needed to pass EMAIL_HOST_PASSWORD as a bytearray to get emails working without with webfaction again

@emg36

emg36 Jan 31, 2017

Why was this changed? I have needed to pass EMAIL_HOST_PASSWORD as a bytearray to get emails working without with webfaction again

This comment has been minimized.

Show comment
Hide comment
@claudep

claudep Jan 31, 2017

Member

On Python 3, force_str is giving a native (unicode) string already, so nothing has changed at this regard.
Use first https://code.djangoproject.com/wiki/TicketClosingReasons/UseSupportChannels to be sure you are not doing something wrong, and open a ticket with a description of the problem if you find that something must be fixed on Django's side.

@claudep

claudep Jan 31, 2017

Member

On Python 3, force_str is giving a native (unicode) string already, so nothing has changed at this regard.
Use first https://code.djangoproject.com/wiki/TicketClosingReasons/UseSupportChannels to be sure you are not doing something wrong, and open a ticket with a description of the problem if you find that something must be fixed on Django's side.

return True
except (smtplib.SMTPException, socket.error):
if not self.fail_silently:
@@ -5,14 +5,14 @@
import os
import sys
from argparse import ArgumentParser
+from io import TextIOBase
import django
from django.core import checks
from django.core.exceptions import ImproperlyConfigured
from django.core.management.color import color_style, no_style
from django.db import DEFAULT_DB_ALIAS, connections
from django.db.migrations.exceptions import MigrationSchemaMissing
-from django.utils.encoding import force_str
class CommandError(Exception):
@@ -73,7 +73,7 @@ def handle_default_options(options):
sys.path.insert(0, options.pythonpath)
-class OutputWrapper:
+class OutputWrapper(TextIOBase):
"""
Wrapper around stdout/stderr
"""
@@ -104,7 +104,7 @@ def write(self, msg, style_func=None, ending=None):
if ending and not msg.endswith(ending):
msg += ending
style_func = style_func or self.style_func
- self._out.write(force_str(style_func(msg)))
+ self._out.write(style_func(msg))
class BaseCommand:
@@ -377,9 +377,9 @@ def check(self, app_configs=None, tags=None, display_num_errors=False,
if issues:
visible_issue_count += len(issues)
formatted = (
- self.style.ERROR(force_str(e))
+ self.style.ERROR(str(e))
if e.is_serious()
- else self.style.WARNING(force_str(e))
+ else self.style.WARNING(str(e))
for e in issues)
formatted = "\n".join(sorted(formatted))
body += '\n%s:\n%s\n' % (group_name, formatted)
@@ -15,7 +15,7 @@
find_command, handle_extensions, popen_wrapper,
)
from django.utils._os import upath
-from django.utils.encoding import DEFAULT_LOCALE_ENCODING, force_str
+from django.utils.encoding import DEFAULT_LOCALE_ENCODING
from django.utils.functional import cached_property
from django.utils.jslex import prepare_js_for_gettext
from django.utils.text import get_text_list
@@ -557,7 +557,7 @@ def process_locale_dir(self, locale_dir, files):
input_files = [bf.work_path for bf in build_files]
with NamedTemporaryFile(mode='w+') as input_files_list:
- input_files_list.write(force_str('\n'.join(input_files), encoding=DEFAULT_LOCALE_ENCODING))
+ input_files_list.write(('\n'.join(input_files)))
input_files_list.flush()
args.extend(['--files-from', input_files_list.name])
args.extend(self.xgettext_options)
@@ -649,7 +649,7 @@ def copy_plural_forms(self, msgs, locale):
with open(django_po, 'r', encoding='utf-8') as fp:
m = plural_forms_re.search(fp.read())
if m:
- plural_form_line = force_str(m.group('value'))
+ plural_form_line = m.group('value')
if self.verbosity > 1:
self.stdout.write("copying plural forms: %s\n" % plural_form_line)
lines = []
View
@@ -43,7 +43,7 @@
from django.conf import settings
from django.utils import baseconv
from django.utils.crypto import constant_time_compare, salted_hmac
-from django.utils.encoding import force_bytes, force_str, force_text
+from django.utils.encoding import force_bytes, force_text
from django.utils.module_loading import import_string
_SEP_UNSAFE = re.compile(r'^[A-z0-9-_=]*$')
@@ -152,25 +152,21 @@ class Signer:
def __init__(self, key=None, sep=':', salt=None):
# Use of native strings in all versions of Python
self.key = key or settings.SECRET_KEY
- self.sep = force_str(sep)
+ self.sep = sep
if _SEP_UNSAFE.match(self.sep):
raise ValueError(
'Unsafe Signer separator: %r (cannot be empty or consist of '
'only A-z0-9-_=)' % sep,
)
- self.salt = force_str(salt or '%s.%s' % (self.__class__.__module__, self.__class__.__name__))
+ self.salt = salt or '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
def signature(self, value):
- signature = base64_hmac(self.salt + 'signer', value, self.key)
- # Convert the signature from bytes to str only on Python 3
- return force_str(signature)
+ return force_text(base64_hmac(self.salt + 'signer', value, self.key))
def sign(self, value):
- value = force_str(value)
- return str('%s%s%s') % (value, self.sep, self.signature(value))
+ return '%s%s%s' % (value, self.sep, self.signature(value))
def unsign(self, signed_value):
- signed_value = force_str(signed_value)
if self.sep not in signed_value:
raise BadSignature('No "%s" found in value' % self.sep)
value, sig = signed_value.rsplit(self.sep, 1)
@@ -185,8 +181,7 @@ def timestamp(self):
return baseconv.base62.encode(int(time.time()))
def sign(self, value):
- value = force_str(value)
- value = str('%s%s%s') % (value, self.sep, self.timestamp())
+ value = '%s%s%s' % (force_text(value), self.sep, self.timestamp())
return super(TimestampSigner, self).sign(value)
def unsign(self, value, max_age=None):
@@ -12,7 +12,6 @@
from django.db.backends import utils as backend_utils
from django.db.backends.base.base import BaseDatabaseWrapper
from django.utils import six
-from django.utils.encoding import force_str
from django.utils.functional import cached_property
from django.utils.safestring import SafeBytes, SafeText
@@ -225,7 +224,7 @@ def get_connection_params(self):
if settings_dict['NAME']:
kwargs['db'] = settings_dict['NAME']
if settings_dict['PASSWORD']:
- kwargs['passwd'] = force_str(settings_dict['PASSWORD'])
+ kwargs['passwd'] = settings_dict['PASSWORD']
if settings_dict['HOST'].startswith('/'):
kwargs['unix_socket'] = settings_dict['HOST']
elif settings_dict['HOST']:
@@ -12,7 +12,6 @@
from django.db import DEFAULT_DB_ALIAS
from django.db.backends.base.base import BaseDatabaseWrapper
from django.db.utils import DatabaseError as WrappedDatabaseError
-from django.utils.encoding import force_str
from django.utils.functional import cached_property
from django.utils.safestring import SafeBytes, SafeText
@@ -160,7 +159,7 @@ def get_connection_params(self):
if settings_dict['USER']:
conn_params['user'] = settings_dict['USER']
if settings_dict['PASSWORD']:
- conn_params['password'] = force_str(settings_dict['PASSWORD'])
+ conn_params['password'] = settings_dict['PASSWORD']
if settings_dict['HOST']:
conn_params['host'] = settings_dict['HOST']
if settings_dict['PORT']:
Oops, something went wrong.

0 comments on commit dc8834c

Please sign in to comment.