replace force_text with force_str

This commit is contained in:
Gregory N. Schmit 2019-07-29 19:02:43 -05:00 committed by Carlton Gibson
parent b45ff07294
commit 335054a5d3
12 changed files with 52 additions and 52 deletions

View File

@ -7,7 +7,7 @@ In addition Django's built in 403 and 404 exceptions are handled.
import math import math
from django.http import JsonResponse from django.http import JsonResponse
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.utils.translation import ngettext from django.utils.translation import ngettext
@ -36,7 +36,7 @@ def _get_error_details(data, default_code=None):
return ReturnDict(ret, serializer=data.serializer) return ReturnDict(ret, serializer=data.serializer)
return ret return ret
text = force_text(data) text = force_str(data)
code = getattr(data, 'code', default_code) code = getattr(data, 'code', default_code)
return ErrorDetail(text, code) return ErrorDetail(text, code)
@ -191,7 +191,7 @@ class MethodNotAllowed(APIException):
def __init__(self, method, detail=None, code=None): def __init__(self, method, detail=None, code=None):
if detail is None: if detail is None:
detail = force_text(self.default_detail).format(method=method) detail = force_str(self.default_detail).format(method=method)
super().__init__(detail, code) super().__init__(detail, code)
@ -212,7 +212,7 @@ class UnsupportedMediaType(APIException):
def __init__(self, media_type, detail=None, code=None): def __init__(self, media_type, detail=None, code=None):
if detail is None: if detail is None:
detail = force_text(self.default_detail).format(media_type=media_type) detail = force_str(self.default_detail).format(media_type=media_type)
super().__init__(detail, code) super().__init__(detail, code)
@ -225,12 +225,12 @@ class Throttled(APIException):
def __init__(self, wait=None, detail=None, code=None): def __init__(self, wait=None, detail=None, code=None):
if detail is None: if detail is None:
detail = force_text(self.default_detail) detail = force_str(self.default_detail)
if wait is not None: if wait is not None:
wait = math.ceil(wait) wait = math.ceil(wait)
detail = ' '.join(( detail = ' '.join((
detail, detail,
force_text(ngettext(self.extra_detail_singular.format(wait=wait), force_str(ngettext(self.extra_detail_singular.format(wait=wait),
self.extra_detail_plural.format(wait=wait), self.extra_detail_plural.format(wait=wait),
wait)))) wait))))
self.wait = wait self.wait = wait

View File

@ -10,7 +10,7 @@ from django.db import models
from django.db.models.constants import LOOKUP_SEP from django.db.models.constants import LOOKUP_SEP
from django.db.models.sql.constants import ORDER_PATTERN from django.db.models.sql.constants import ORDER_PATTERN
from django.template import loader from django.template import loader
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from rest_framework.compat import coreapi, coreschema, distinct from rest_framework.compat import coreapi, coreschema, distinct
@ -151,8 +151,8 @@ class SearchFilter(BaseFilterBackend):
required=False, required=False,
location='query', location='query',
schema=coreschema.String( schema=coreschema.String(
title=force_text(self.search_title), title=force_str(self.search_title),
description=force_text(self.search_description) description=force_str(self.search_description)
) )
) )
] ]
@ -163,7 +163,7 @@ class SearchFilter(BaseFilterBackend):
'name': self.search_param, 'name': self.search_param,
'required': False, 'required': False,
'in': 'query', 'in': 'query',
'description': force_text(self.search_description), 'description': force_str(self.search_description),
'schema': { 'schema': {
'type': 'string', 'type': 'string',
}, },
@ -295,8 +295,8 @@ class OrderingFilter(BaseFilterBackend):
required=False, required=False,
location='query', location='query',
schema=coreschema.String( schema=coreschema.String(
title=force_text(self.ordering_title), title=force_str(self.ordering_title),
description=force_text(self.ordering_description) description=force_str(self.ordering_description)
) )
) )
] ]
@ -307,7 +307,7 @@ class OrderingFilter(BaseFilterBackend):
'name': self.ordering_param, 'name': self.ordering_param,
'required': False, 'required': False,
'in': 'query', 'in': 'query',
'description': force_text(self.ordering_description), 'description': force_str(self.ordering_description),
'schema': { 'schema': {
'type': 'string', 'type': 'string',
}, },

View File

@ -10,7 +10,7 @@ from collections import OrderedDict
from django.core.exceptions import PermissionDenied from django.core.exceptions import PermissionDenied
from django.http import Http404 from django.http import Http404
from django.utils.encoding import force_text from django.utils.encoding import force_str
from rest_framework import exceptions, serializers from rest_framework import exceptions, serializers
from rest_framework.request import clone_request from rest_framework.request import clone_request
@ -130,7 +130,7 @@ class SimpleMetadata(BaseMetadata):
for attr in attrs: for attr in attrs:
value = getattr(field, attr, None) value = getattr(field, attr, None)
if value is not None and value != '': if value is not None and value != '':
field_info[attr] = force_text(value, strings_only=True) field_info[attr] = force_str(value, strings_only=True)
if getattr(field, 'child', None): if getattr(field, 'child', None):
field_info['child'] = self.get_field_info(field.child) field_info['child'] = self.get_field_info(field.child)
@ -143,7 +143,7 @@ class SimpleMetadata(BaseMetadata):
field_info['choices'] = [ field_info['choices'] = [
{ {
'value': choice_value, 'value': choice_value,
'display_name': force_text(choice_name, strings_only=True) 'display_name': force_str(choice_name, strings_only=True)
} }
for choice_value, choice_name in field.choices.items() for choice_value, choice_name in field.choices.items()
] ]

View File

@ -9,7 +9,7 @@ from urllib import parse
from django.core.paginator import InvalidPage from django.core.paginator import InvalidPage
from django.core.paginator import Paginator as DjangoPaginator from django.core.paginator import Paginator as DjangoPaginator
from django.template import loader from django.template import loader
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from rest_framework.compat import coreapi, coreschema from rest_framework.compat import coreapi, coreschema
@ -286,7 +286,7 @@ class PageNumberPagination(BasePagination):
location='query', location='query',
schema=coreschema.Integer( schema=coreschema.Integer(
title='Page', title='Page',
description=force_text(self.page_query_description) description=force_str(self.page_query_description)
) )
) )
] ]
@ -298,7 +298,7 @@ class PageNumberPagination(BasePagination):
location='query', location='query',
schema=coreschema.Integer( schema=coreschema.Integer(
title='Page size', title='Page size',
description=force_text(self.page_size_query_description) description=force_str(self.page_size_query_description)
) )
) )
) )
@ -310,7 +310,7 @@ class PageNumberPagination(BasePagination):
'name': self.page_query_param, 'name': self.page_query_param,
'required': False, 'required': False,
'in': 'query', 'in': 'query',
'description': force_text(self.page_query_description), 'description': force_str(self.page_query_description),
'schema': { 'schema': {
'type': 'integer', 'type': 'integer',
}, },
@ -322,7 +322,7 @@ class PageNumberPagination(BasePagination):
'name': self.page_size_query_param, 'name': self.page_size_query_param,
'required': False, 'required': False,
'in': 'query', 'in': 'query',
'description': force_text(self.page_size_query_description), 'description': force_str(self.page_size_query_description),
'schema': { 'schema': {
'type': 'integer', 'type': 'integer',
}, },
@ -478,7 +478,7 @@ class LimitOffsetPagination(BasePagination):
location='query', location='query',
schema=coreschema.Integer( schema=coreschema.Integer(
title='Limit', title='Limit',
description=force_text(self.limit_query_description) description=force_str(self.limit_query_description)
) )
), ),
coreapi.Field( coreapi.Field(
@ -487,7 +487,7 @@ class LimitOffsetPagination(BasePagination):
location='query', location='query',
schema=coreschema.Integer( schema=coreschema.Integer(
title='Offset', title='Offset',
description=force_text(self.offset_query_description) description=force_str(self.offset_query_description)
) )
) )
] ]
@ -498,7 +498,7 @@ class LimitOffsetPagination(BasePagination):
'name': self.limit_query_param, 'name': self.limit_query_param,
'required': False, 'required': False,
'in': 'query', 'in': 'query',
'description': force_text(self.limit_query_description), 'description': force_str(self.limit_query_description),
'schema': { 'schema': {
'type': 'integer', 'type': 'integer',
}, },
@ -507,7 +507,7 @@ class LimitOffsetPagination(BasePagination):
'name': self.offset_query_param, 'name': self.offset_query_param,
'required': False, 'required': False,
'in': 'query', 'in': 'query',
'description': force_text(self.offset_query_description), 'description': force_str(self.offset_query_description),
'schema': { 'schema': {
'type': 'integer', 'type': 'integer',
}, },
@ -861,7 +861,7 @@ class CursorPagination(BasePagination):
location='query', location='query',
schema=coreschema.String( schema=coreschema.String(
title='Cursor', title='Cursor',
description=force_text(self.cursor_query_description) description=force_str(self.cursor_query_description)
) )
) )
] ]
@ -873,7 +873,7 @@ class CursorPagination(BasePagination):
location='query', location='query',
schema=coreschema.Integer( schema=coreschema.Integer(
title='Page size', title='Page size',
description=force_text(self.page_size_query_description) description=force_str(self.page_size_query_description)
) )
) )
) )
@ -885,7 +885,7 @@ class CursorPagination(BasePagination):
'name': self.cursor_query_param, 'name': self.cursor_query_param,
'required': False, 'required': False,
'in': 'query', 'in': 'query',
'description': force_text(self.cursor_query_description), 'description': force_str(self.cursor_query_description),
'schema': { 'schema': {
'type': 'integer', 'type': 'integer',
}, },
@ -897,7 +897,7 @@ class CursorPagination(BasePagination):
'name': self.page_size_query_param, 'name': self.page_size_query_param,
'required': False, 'required': False,
'in': 'query', 'in': 'query',
'description': force_text(self.page_size_query_description), 'description': force_str(self.page_size_query_description),
'schema': { 'schema': {
'type': 'integer', 'type': 'integer',
}, },

View File

@ -14,7 +14,7 @@ from django.http.multipartparser import ChunkIter
from django.http.multipartparser import \ from django.http.multipartparser import \
MultiPartParser as DjangoMultiPartParser MultiPartParser as DjangoMultiPartParser
from django.http.multipartparser import MultiPartParserError, parse_header from django.http.multipartparser import MultiPartParserError, parse_header
from django.utils.encoding import force_text from django.utils.encoding import force_str
from rest_framework import renderers from rest_framework import renderers
from rest_framework.exceptions import ParseError from rest_framework.exceptions import ParseError
@ -205,7 +205,7 @@ class FileUploadParser(BaseParser):
filename_parm = disposition[1] filename_parm = disposition[1]
if 'filename*' in filename_parm: if 'filename*' in filename_parm:
return self.get_encoded_filename(filename_parm) return self.get_encoded_filename(filename_parm)
return force_text(filename_parm['filename']) return force_str(filename_parm['filename'])
except (AttributeError, KeyError, ValueError): except (AttributeError, KeyError, ValueError):
pass pass
@ -214,10 +214,10 @@ class FileUploadParser(BaseParser):
Handle encoded filenames per RFC6266. See also: Handle encoded filenames per RFC6266. See also:
https://tools.ietf.org/html/rfc2231#section-4 https://tools.ietf.org/html/rfc2231#section-4
""" """
encoded_filename = force_text(filename_parm['filename*']) encoded_filename = force_str(filename_parm['filename*'])
try: try:
charset, lang, filename = encoded_filename.split('\'', 2) charset, lang, filename = encoded_filename.split('\'', 2)
filename = parse.unquote(filename) filename = parse.unquote(filename)
except (ValueError, LookupError): except (ValueError, LookupError):
filename = force_text(filename_parm['filename']) filename = force_str(filename_parm['filename'])
return filename return filename

View File

@ -4,7 +4,7 @@ from collections import Counter, OrderedDict
from urllib import parse from urllib import parse
from django.db import models from django.db import models
from django.utils.encoding import force_text, smart_text from django.utils.encoding import force_str, smart_text
from rest_framework import exceptions, serializers from rest_framework import exceptions, serializers
from rest_framework.compat import coreapi, coreschema, uritemplate from rest_framework.compat import coreapi, coreschema, uritemplate
@ -255,8 +255,8 @@ class SchemaGenerator(BaseSchemaGenerator):
def field_to_schema(field): def field_to_schema(field):
title = force_text(field.label) if field.label else '' title = force_str(field.label) if field.label else ''
description = force_text(field.help_text) if field.help_text else '' description = force_str(field.help_text) if field.help_text else ''
if isinstance(field, (serializers.ListSerializer, serializers.ListField)): if isinstance(field, (serializers.ListSerializer, serializers.ListField)):
child_schema = field_to_schema(field.child) child_schema = field_to_schema(field.child)
@ -457,10 +457,10 @@ class AutoSchema(ViewInspector):
model_field = None model_field = None
if model_field is not None and model_field.verbose_name: if model_field is not None and model_field.verbose_name:
title = force_text(model_field.verbose_name) title = force_str(model_field.verbose_name)
if model_field is not None and model_field.help_text: if model_field is not None and model_field.help_text:
description = force_text(model_field.help_text) description = force_str(model_field.help_text)
elif model_field is not None and model_field.primary_key: elif model_field is not None and model_field.primary_key:
description = get_pk_description(model, model_field) description = get_pk_description(model, model_field)

View File

@ -6,7 +6,7 @@ from django.core.validators import (
MinLengthValidator, MinValueValidator, RegexValidator, URLValidator MinLengthValidator, MinValueValidator, RegexValidator, URLValidator
) )
from django.db import models from django.db import models
from django.utils.encoding import force_text from django.utils.encoding import force_str
from rest_framework import exceptions, serializers from rest_framework import exceptions, serializers
from rest_framework.compat import uritemplate from rest_framework.compat import uritemplate
@ -162,7 +162,7 @@ class AutoSchema(ViewInspector):
model_field = None model_field = None
if model_field is not None and model_field.help_text: if model_field is not None and model_field.help_text:
description = force_text(model_field.help_text) description = force_str(model_field.help_text)
elif model_field is not None and model_field.primary_key: elif model_field is not None and model_field.primary_key:
description = get_pk_description(model, model_field) description = get_pk_description(model, model_field)

View File

@ -4,7 +4,7 @@ from collections import OrderedDict
from django import template from django import template
from django.template import loader from django.template import loader
from django.urls import NoReverseMatch, reverse from django.urls import NoReverseMatch, reverse
from django.utils.encoding import force_text, iri_to_uri from django.utils.encoding import force_str, iri_to_uri
from django.utils.html import escape, format_html, smart_urlquote from django.utils.html import escape, format_html, smart_urlquote
from django.utils.safestring import SafeData, mark_safe from django.utils.safestring import SafeData, mark_safe
@ -339,7 +339,7 @@ def urlize_quoted_links(text, trim_url_limit=None, nofollow=True, autoescape=Tru
def conditional_escape(text): def conditional_escape(text):
return escape(text) if autoescape and not safe_input else text return escape(text) if autoescape and not safe_input else text
words = word_split_re.split(force_text(text)) words = word_split_re.split(force_str(text))
for i, word in enumerate(words): for i, word in enumerate(words):
if '.' in word or '@' in word or ':' in word: if '.' in word or '@' in word or ':' in word:
# Deal with punctuation. # Deal with punctuation.

View File

@ -8,7 +8,7 @@ import uuid
from django.db.models.query import QuerySet from django.db.models.query import QuerySet
from django.utils import timezone from django.utils import timezone
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 rest_framework.compat import coreapi from rest_framework.compat import coreapi
@ -23,7 +23,7 @@ class JSONEncoder(json.JSONEncoder):
# For Date Time string spec, see ECMA 262 # For Date Time string spec, see ECMA 262
# https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15 # https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
if isinstance(obj, Promise): if isinstance(obj, Promise):
return force_text(obj) return force_str(obj)
elif isinstance(obj, datetime.datetime): elif isinstance(obj, datetime.datetime):
representation = obj.isoformat() representation = obj.isoformat()
if representation.endswith('+00:00'): if representation.endswith('+00:00'):

View File

@ -3,7 +3,7 @@ Utility functions to return a formatted name and description for a given view.
""" """
import re import re
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.utils.html import escape from django.utils.html import escape
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
@ -29,7 +29,7 @@ def dedent(content):
as it fails to dedent multiline docstrings that include as it fails to dedent multiline docstrings that include
unindented text on the initial line. unindented text on the initial line.
""" """
content = force_text(content) content = force_str(content)
lines = [line for line in content.splitlines()[1:] if line.lstrip()] lines = [line for line in content.splitlines()[1:] if line.lstrip()]
# unindent the content if needed # unindent the content if needed

View File

@ -5,7 +5,7 @@ of serializer classes and serializer fields.
import re import re
from django.db import models from django.db import models
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
@ -28,7 +28,7 @@ def smart_repr(value):
return manager_repr(value) return manager_repr(value)
if isinstance(value, Promise) and value._delegate_text: if isinstance(value, Promise) and value._delegate_text:
value = force_text(value) value = force_str(value)
value = repr(value) value = repr(value)

View File

@ -1,7 +1,7 @@
from collections import OrderedDict from collections import OrderedDict
from collections.abc import MutableMapping from collections.abc import MutableMapping
from django.utils.encoding import force_text from django.utils.encoding import force_str
from rest_framework.utils import json from rest_framework.utils import json
@ -123,7 +123,7 @@ class NestedBoundField(BoundField):
if isinstance(value, (list, dict)): if isinstance(value, (list, dict)):
values[key] = value values[key] = value
else: else:
values[key] = '' if (value is None or value is False) else force_text(value) values[key] = '' if (value is None or value is False) else force_str(value)
return self.__class__(self._field, values, self.errors, self._prefix) return self.__class__(self._field, values, self.errors, self._prefix)