Address RemovedInDjango40Warning (1)

force_text() is deprecated in favor of force_str()
smart_text() is deprecated in favor of smart_str()

https://docs.djangoproject.com/en/4.0/releases/3.0/#django-utils-encoding-force-text-and-smart-text

Change-Id: Ic462fa8c3dfa26e8196df19fef5044036a9e97b4
This commit is contained in:
Akihiro Motoki 2022-01-26 22:40:11 +09:00
parent 047b81e979
commit a9d5273f3c
18 changed files with 53 additions and 55 deletions

View File

@ -263,8 +263,8 @@ HANDLE_EXC_METHODS = [
def _append_detail(message, details): def _append_detail(message, details):
return encoding.force_text(message) + SEPARATOR + \ return encoding.force_str(message) + SEPARATOR + \
encoding.force_text(details) encoding.force_str(details)
def handle(request, message=None, redirect=None, ignore=False, def handle(request, message=None, redirect=None, ignore=False,
@ -315,7 +315,7 @@ def handle(request, message=None, redirect=None, ignore=False,
exc_type, exc_value, exc_traceback = exc_value.wrapped exc_type, exc_value, exc_traceback = exc_value.wrapped
wrap = True wrap = True
log_entry = encoding.force_text(exc_value) log_entry = encoding.force_str(exc_value)
user_message = "" user_message = ""
# We trust messages from our own exceptions # We trust messages from our own exceptions
@ -323,9 +323,9 @@ def handle(request, message=None, redirect=None, ignore=False,
user_message = log_entry user_message = log_entry
# If the message has a placeholder for the exception, fill it in # If the message has a placeholder for the exception, fill it in
elif message and "%(exc)s" in message: elif message and "%(exc)s" in message:
user_message = encoding.force_text(message) % {"exc": log_entry} user_message = encoding.force_str(message) % {"exc": log_entry}
elif message: elif message:
user_message = encoding.force_text(message) user_message = encoding.force_str(message)
if details is None: if details is None:
user_message = _append_detail(user_message, exc_value) user_message = _append_detail(user_message, exc_value)
elif details: elif details:

View File

@ -27,7 +27,7 @@ from django.forms.utils import flatatt
from django.forms import widgets from django.forms import widgets
from django.template.loader import get_template from django.template.loader import get_template
from django import urls from django import urls
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.utils.functional import Promise from django.utils.functional import Promise
from django.utils import html from django.utils import html
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
@ -242,7 +242,7 @@ class SelectWidget(widgets.Widget):
return attrs return attrs
def render_option(self, selected_choices, option_value, option_label): def render_option(self, selected_choices, option_value, option_label):
option_value = force_text(option_value) option_value = force_str(option_value)
other_html = (' selected="selected"' other_html = (' selected="selected"'
if option_value in selected_choices else '') if option_value in selected_choices else '')
@ -259,12 +259,12 @@ class SelectWidget(widgets.Widget):
def render_options(self, selected_choices): def render_options(self, selected_choices):
# Normalize to strings. # Normalize to strings.
selected_choices = set(force_text(v) for v in selected_choices) selected_choices = set(force_str(v) for v in selected_choices)
output = [] output = []
for option_value, option_label in self.choices: for option_value, option_label in self.choices:
if isinstance(option_label, (list, tuple)): if isinstance(option_label, (list, tuple)):
output.append(html.format_html( output.append(html.format_html(
'<optgroup label="{}">', force_text(option_value))) '<optgroup label="{}">', force_str(option_value)))
for option in option_label: for option in option_label:
output.append( output.append(
self.render_option(selected_choices, *option)) self.render_option(selected_choices, *option))
@ -279,8 +279,7 @@ class SelectWidget(widgets.Widget):
if not isinstance(option_label, (str, Promise)): if not isinstance(option_label, (str, Promise)):
for data_attr in self.data_attrs: for data_attr in self.data_attrs:
data_value = html.conditional_escape( data_value = html.conditional_escape(
force_text(getattr(option_label, force_str(getattr(option_label, data_attr, "")))
data_attr, "")))
other_html.append('data-%s="%s"' % (data_attr, data_value)) other_html.append('data-%s="%s"' % (data_attr, data_value))
return ' '.join(other_html) return ' '.join(other_html)
@ -288,7 +287,7 @@ class SelectWidget(widgets.Widget):
if (not isinstance(option_label, (str, Promise)) and if (not isinstance(option_label, (str, Promise)) and
callable(self.transform)): callable(self.transform)):
option_label = self.transform(option_label) option_label = self.transform(option_label)
return html.conditional_escape(force_text(option_label)) return html.conditional_escape(force_str(option_label))
def transform_option_html_attrs(self, option_label): def transform_option_html_attrs(self, option_label):
if not callable(self.transform_html_attrs): if not callable(self.transform_html_attrs):
@ -473,8 +472,8 @@ class ChoiceInput(SubWidget):
self.name = name self.name = name
self.value = value self.value = value
self.attrs = attrs self.attrs = attrs
self.choice_value = force_text(choice[0]) self.choice_value = force_str(choice[0])
self.choice_label = force_text(choice[1]) self.choice_label = force_str(choice[1])
self.index = index self.index = index
if 'id' in self.attrs: if 'id' in self.attrs:
self.attrs['id'] += "_%d" % self.index self.attrs['id'] += "_%d" % self.index
@ -529,7 +528,7 @@ class ThemableCheckboxChoiceInput(ChoiceInput):
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
# NOTE(e0ne): Django sets default value to None # NOTE(e0ne): Django sets default value to None
if self.value: if self.value:
self.value = set(force_text(v) for v in self.value) self.value = set(force_str(v) for v in self.value)
def is_checked(self): def is_checked(self):
if self.value: if self.value:
@ -589,7 +588,7 @@ class ThemableCheckboxSelectMultiple(widgets.CheckboxSelectMultiple):
self.name, self.value, self.attrs.copy(), choice, i) self.name, self.value, self.attrs.copy(), choice, i)
output.append(html.format_html( output.append(html.format_html(
self.inner_html, self.inner_html,
choice_value=force_text(w), choice_value=force_str(w),
sub_widgets='')) sub_widgets=''))
return html.format_html( return html.format_html(
self.outer_html, self.outer_html,

View File

@ -19,12 +19,12 @@ messaging needs (e.g. AJAX communication, etc.).
from django.contrib import messages as _messages from django.contrib import messages as _messages
from django.contrib.messages import constants from django.contrib.messages import constants
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.utils.safestring import SafeData from django.utils.safestring import SafeData
def horizon_message_already_queued(request, message): def horizon_message_already_queued(request, message):
_message = force_text(message) _message = force_str(message)
if request.is_ajax(): if request.is_ajax():
for tag, msg, extra in request.horizon['async_messages']: for tag, msg, extra in request.horizon['async_messages']:
if _message == msg: if _message == msg:
@ -46,7 +46,7 @@ def add_message(request, level, message, extra_tags='', fail_silently=False):
if isinstance(message, SafeData): if isinstance(message, SafeData):
extra_tags = extra_tags + ' safe' extra_tags = extra_tags + ' safe'
request.horizon['async_messages'].append([tag, request.horizon['async_messages'].append([tag,
force_text(message), force_str(message),
extra_tags]) extra_tags])
else: else:
return _messages.add_message(request, level, message, return _messages.add_message(request, level, message,

View File

@ -730,7 +730,7 @@ class Cell(html.HTMLElement):
# those columns where truncate is False leads to multiple errors # those columns where truncate is False leads to multiple errors
# in unit tests # in unit tests
data = getattr(datum, column.name, '') or '' data = getattr(datum, column.name, '') or ''
data = encoding.force_text(data) data = encoding.force_str(data)
if len(data) > column.truncate: if len(data) > column.truncate:
self.attrs['data-toggle'] = 'tooltip' self.attrs['data-toggle'] = 'tooltip'
self.attrs['title'] = data self.attrs['title'] = data

View File

@ -17,7 +17,7 @@ from collections import OrderedDict
from django.conf import settings from django.conf import settings
from django import template from django import template
from django.template import Node from django.template import Node
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.utils import translation from django.utils import translation
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
@ -34,7 +34,7 @@ class MinifiedNode(Node):
def render(self, context): def render(self, context):
return ' '.join( return ' '.join(
force_text(self.nodelist.render(context).strip()).split() force_str(self.nodelist.render(context).strip()).split()
).replace(' > ', '>').replace(' <', '<') ).replace(' > ', '>').replace(' <', '<')
@ -142,9 +142,9 @@ def quota(val, units=None):
if val == float("inf"): if val == float("inf"):
return _("(No Limit)") return _("(No Limit)")
if units is not None: if units is not None:
return "%s %s %s" % (val, force_text(units), return "%s %s %s" % (val, force_str(units),
force_text(_("Available"))) force_str(_("Available")))
return "%s %s" % (val, force_text(_("Available"))) return "%s %s" % (val, force_str(_("Available")))
@register.filter @register.filter

View File

@ -38,7 +38,7 @@ from django import test as django_test
from django.test.client import RequestFactory from django.test.client import RequestFactory
from django.test import tag from django.test import tag
from django.test import utils as django_test_utils from django.test import utils as django_test_utils
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.contrib.staticfiles.testing \ from django.contrib.staticfiles.testing \
import StaticLiveServerTestCase as LiveServerTestCase import StaticLiveServerTestCase as LiveServerTestCase
@ -230,7 +230,7 @@ class TestCase(django_test.TestCase):
# Otherwise, make sure we got the expected messages. # Otherwise, make sure we got the expected messages.
for msg_type, count in kwargs.items(): for msg_type, count in kwargs.items():
msgs = [force_text(m.message) msgs = [force_str(m.message)
for m in messages if msg_type in m.tags] for m in messages if msg_type in m.tags]
assert len(msgs) == count, \ assert len(msgs) == count, \
"%s messages not as expected: %s" % (msg_type.title(), "%s messages not as expected: %s" % (msg_type.title(),

View File

@ -375,7 +375,7 @@ class GetUserHomeTests(test.TestCase):
base.Horizon.get_user_home(self.test_user)) base.Horizon.get_user_home(self.test_user))
def test_using_module_function(self): def test_using_module_function(self):
module_func = 'django.utils.encoding.force_text' module_func = 'django.utils.encoding.force_str'
settings.HORIZON_CONFIG['user_home'] = module_func settings.HORIZON_CONFIG['user_home'] = module_func
conf.HORIZON_CONFIG._setup() conf.HORIZON_CONFIG._setup()

View File

@ -10,7 +10,7 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from django.utils.encoding import force_text from django.utils.encoding import force_str
from horizon import exceptions from horizon import exceptions
from horizon.test import helpers as test from horizon.test import helpers as test
@ -25,7 +25,7 @@ class HandleTests(test.TestCase):
# Japanese translation of: # Japanese translation of:
# 'Because the container is not empty, it can not be deleted.' # 'Because the container is not empty, it can not be deleted.'
expected = ['error', force_text(translated_unicode + expected = ['error', force_str(translated_unicode +
exceptions.SEPARATOR + exceptions.SEPARATOR +
translated_unicode), ''] translated_unicode), '']

View File

@ -15,7 +15,7 @@
import json import json
from django import http from django import http
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from horizon import messages from horizon import messages
@ -27,7 +27,7 @@ class MessageTests(test.TestCase):
def test_middleware_header(self): def test_middleware_header(self):
req = self.request req = self.request
string = "Giant ants are attacking San Francisco!" string = "Giant ants are attacking San Francisco!"
expected = ["error", force_text(string), ""] expected = ["error", force_str(string), ""]
self.assertIn("async_messages", req.horizon) self.assertIn("async_messages", req.horizon)
self.assertCountEqual(req.horizon['async_messages'], []) self.assertCountEqual(req.horizon['async_messages'], [])
req.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' req.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
@ -42,7 +42,7 @@ class MessageTests(test.TestCase):
def test_error_message(self): def test_error_message(self):
req = self.request req = self.request
string = mark_safe("We are now safe from ants! Go <a>here</a>!") string = mark_safe("We are now safe from ants! Go <a>here</a>!")
expected = ["error", force_text(string), " safe"] expected = ["error", force_str(string), " safe"]
self.assertIn("async_messages", req.horizon) self.assertIn("async_messages", req.horizon)
self.assertCountEqual(req.horizon['async_messages'], []) self.assertCountEqual(req.horizon['async_messages'], [])
req.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' req.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'

View File

@ -20,14 +20,13 @@ from oslo_utils import units
from django.conf import settings from django.conf import settings
from django.contrib.auth import logout from django.contrib.auth import logout
from django import http from django import http
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.utils.functional import lazy from django.utils.functional import lazy
from django.utils import translation from django.utils import translation
def _lazy_join(separator, strings): def _lazy_join(separator, strings):
return separator.join([force_text(s) return separator.join([force_str(s) for s in strings])
for s in strings])
lazy_join = lazy(_lazy_join, str) lazy_join = lazy(_lazy_join, str)
@ -43,7 +42,7 @@ def add_logout_reason(request, response, reason, status='success'):
# Store the translated string in the cookie # Store the translated string in the cookie
lang = translation.get_language_from_request(request) lang = translation.get_language_from_request(request)
with translation.override(lang): with translation.override(lang):
reason = force_text(reason).encode('unicode_escape').decode('ascii') reason = force_str(reason).encode('unicode_escape').decode('ascii')
response.set_cookie('logout_reason', reason, max_age=10) response.set_cookie('logout_reason', reason, max_age=10)
response.set_cookie('logout_status', status, max_age=10) response.set_cookie('logout_status', status, max_age=10)

View File

@ -13,7 +13,7 @@
# under the License. # under the License.
from django.core.serializers.json import DjangoJSONEncoder from django.core.serializers.json import DjangoJSONEncoder
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.utils.functional import Promise from django.utils.functional import Promise
@ -21,5 +21,5 @@ class LazyTranslationEncoder(DjangoJSONEncoder):
"""JSON encoder that resolves lazy objects like translations""" """JSON encoder that resolves lazy objects like translations"""
def default(self, obj): def default(self, obj):
if isinstance(obj, Promise): if isinstance(obj, Promise):
return force_text(obj) return force_str(obj)
return super().default(obj) return super().default(obj)

View File

@ -53,9 +53,9 @@ class PageTitleMixin(object):
if "page_title" not in context: if "page_title" not in context:
con = template.Context(context) con = template.Context(context)
# NOTE(sambetts): Use force_text to ensure lazy translations # NOTE(sambetts): Use force_str to ensure lazy translations
# are handled correctly. # are handled correctly.
temp = template.Template(encoding.force_text(self.page_title)) temp = template.Template(encoding.force_str(self.page_title))
context["page_title"] = temp.render(con) context["page_title"] = temp.render(con)
return context return context

View File

@ -26,7 +26,7 @@ from django.template.defaultfilters import linebreaks
from django.template.defaultfilters import safe from django.template.defaultfilters import safe
from django.template.defaultfilters import slugify from django.template.defaultfilters import slugify
from django import urls from django import urls
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.utils import module_loading from django.utils import module_loading
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from openstack_auth import policy from openstack_auth import policy
@ -163,7 +163,7 @@ class Action(forms.Form, metaclass=ActionMetaclass):
self.required_css_class = 'required' self.required_css_class = 'required'
def __str__(self): def __str__(self):
return force_text(self.name) return force_str(self.name)
def __repr__(self): def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self.slug) return "<%s: %s>" % (self.__class__.__name__, self.slug)
@ -182,7 +182,7 @@ class Action(forms.Form, metaclass=ActionMetaclass):
tmpl = template.loader.get_template(self.help_text_template) tmpl = template.loader.get_template(self.help_text_template)
text += tmpl.render(extra_context, self.request) text += tmpl.render(extra_context, self.request)
else: else:
text += linebreaks(force_text(self.help_text)) text += linebreaks(force_str(self.help_text))
return safe(text) return safe(text)
def add_action_error(self, message): def add_action_error(self, message):
@ -310,7 +310,7 @@ class Step(object):
return "<%s: %s>" % (self.__class__.__name__, self.slug) return "<%s: %s>" % (self.__class__.__name__, self.slug)
def __str__(self): def __str__(self):
return force_text(self.name) return force_str(self.name)
def __init__(self, workflow): def __init__(self, workflow):
super().__init__() super().__init__()
@ -453,7 +453,7 @@ class Step(object):
def get_help_text(self): def get_help_text(self):
"""Returns the help text for this step.""" """Returns the help text for this step."""
text = linebreaks(force_text(self.help_text)) text = linebreaks(force_str(self.help_text))
text += self.action.get_help_text() text += self.action.get_help_text()
return safe(text) return safe(text)

View File

@ -155,5 +155,5 @@ class ResizeInstance(workflows.Workflow):
api.nova.server_resize(request, instance_id, flavor, disk_config) api.nova.server_resize(request, instance_id, flavor, disk_config)
return True return True
except Exception as e: except Exception as e:
self.failure_message = encoding.force_text(e) self.failure_message = encoding.force_str(e)
return False return False

View File

@ -278,7 +278,7 @@ class CreateView(forms.ModalFormView):
_("If \"No volume type\" is selected, the volume will be " _("If \"No volume type\" is selected, the volume will be "
"created without a volume type.") "created without a volume type.")
no_type_description = encoding.force_text(message) no_type_description = encoding.force_str(message)
type_descriptions = [{'name': '', type_descriptions = [{'name': '',
'description': no_type_description}] + \ 'description': no_type_description}] + \

View File

@ -120,6 +120,6 @@ class UserSettingsForm(forms.SelfHandlingForm):
with translation.override(lang_code): with translation.override(lang_code):
messages.success(request, messages.success(request,
encoding.force_text(_("Settings saved."))) encoding.force_str(_("Settings saved.")))
return response return response

View File

@ -93,7 +93,7 @@ class Translate(types.ConfigType):
def _formatter(self, value): def _formatter(self, value):
return self.quote_trailing_and_leading_space( return self.quote_trailing_and_leading_space(
encoding.force_text(value)) encoding.force_str(value))
class Literal(types.ConfigType): class Literal(types.ConfigType):
@ -181,7 +181,7 @@ class Literal(types.ConfigType):
return '(%s)' % ', '.join(self._format(value) for value in result) return '(%s)' % ', '.join(self._format(value) for value in result)
if isinstance(result, functional.Promise): if isinstance(result, functional.Promise):
# Lazy translatable string. # Lazy translatable string.
return repr(encoding.force_text(result)) return repr(encoding.force_str(result))
return repr(result) return repr(result)
def _formatter(self, value): def _formatter(self, value):

View File

@ -20,7 +20,7 @@ from django.conf import settings
from django import http from django import http
from django import shortcuts from django import shortcuts
from django import urls from django import urls
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
import django.views.decorators.vary import django.views.decorators.vary
from django.views.generic import TemplateView from django.views.generic import TemplateView
@ -96,7 +96,7 @@ class ExtensibleHeaderView(TemplateView):
response = view.get(self.request) response = view.get(self.request)
rendered_response = response.render() rendered_response = response.render()
packed_response = [view_path.replace('.', '-'), packed_response = [view_path.replace('.', '-'),
smart_text(rendered_response.content)] smart_str(rendered_response.content)]
header_sections.append(packed_response) header_sections.append(packed_response)
except Exception as e: except Exception as e: