Use six.text_type instead of str everywhere

This commit is contained in:
Tom Christie 2014-10-01 13:09:14 +01:00
parent bb2222963f
commit 381771731f
8 changed files with 30 additions and 24 deletions

View File

@ -5,11 +5,12 @@ versions of django/python, and compatibility wrappers around optional packages.
# flake8: noqa # flake8: noqa
from __future__ import unicode_literals from __future__ import unicode_literals
import django
import inspect
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.conf import settings from django.conf import settings
from django.utils import six from django.utils import six
import django
import inspect
# Handle django.utils.encoding rename in 1.5 onwards. # Handle django.utils.encoding rename in 1.5 onwards.
@ -177,12 +178,12 @@ class RequestFactory(DjangoRequestFactory):
r = { r = {
'PATH_INFO': self._get_path(parsed), 'PATH_INFO': self._get_path(parsed),
'QUERY_STRING': force_text(parsed[4]), 'QUERY_STRING': force_text(parsed[4]),
'REQUEST_METHOD': str(method), 'REQUEST_METHOD': six.text_type(method),
} }
if data: if data:
r.update({ r.update({
'CONTENT_LENGTH': len(data), 'CONTENT_LENGTH': len(data),
'CONTENT_TYPE': str(content_type), 'CONTENT_TYPE': six.text_type(content_type),
'wsgi.input': FakePayload(data), 'wsgi.input': FakePayload(data),
}) })
elif django.VERSION <= (1, 4): elif django.VERSION <= (1, 4):

View File

@ -2,7 +2,7 @@ from django import forms
from django.conf import settings from django.conf import settings
from django.core import validators from django.core import validators
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.utils import timezone from django.utils import six, timezone
from django.utils.datastructures import SortedDict from django.utils.datastructures import SortedDict
from django.utils.dateparse import parse_date, parse_datetime, parse_time from django.utils.dateparse import parse_date, parse_datetime, parse_time
from django.utils.encoding import is_protected_type from django.utils.encoding import is_protected_type
@ -431,10 +431,10 @@ class CharField(Field):
return super(CharField, self).run_validation(data) return super(CharField, self).run_validation(data)
def to_internal_value(self, data): def to_internal_value(self, data):
return str(data) return six.text_type(data)
def to_representation(self, value): def to_representation(self, value):
return str(value) return six.text_type(value)
class EmailField(CharField): class EmailField(CharField):
@ -448,10 +448,10 @@ class EmailField(CharField):
self.validators.append(validator) self.validators.append(validator)
def to_internal_value(self, data): def to_internal_value(self, data):
return str(data).strip() return six.text_type(data).strip()
def to_representation(self, value): def to_representation(self, value):
return str(value).strip() return six.text_type(value).strip()
class RegexField(CharField): class RegexField(CharField):
@ -510,7 +510,7 @@ class IntegerField(Field):
def to_internal_value(self, data): def to_internal_value(self, data):
try: try:
data = int(str(data)) data = int(six.text_type(data))
except (ValueError, TypeError): except (ValueError, TypeError):
self.fail('invalid') self.fail('invalid')
return data return data
@ -616,7 +616,7 @@ class DecimalField(Field):
def to_representation(self, value): def to_representation(self, value):
if not isinstance(value, decimal.Decimal): if not isinstance(value, decimal.Decimal):
value = decimal.Decimal(str(value).strip()) value = decimal.Decimal(six.text_type(value).strip())
context = decimal.getcontext().copy() context = decimal.getcontext().copy()
context.prec = self.max_digits context.prec = self.max_digits
@ -832,19 +832,19 @@ class ChoiceField(Field):
# Allows us to deal with eg. integer choices while supporting either # Allows us to deal with eg. integer choices while supporting either
# integer or string input, but still get the correct datatype out. # integer or string input, but still get the correct datatype out.
self.choice_strings_to_values = dict([ self.choice_strings_to_values = dict([
(str(key), key) for key in self.choices.keys() (six.text_type(key), key) for key in self.choices.keys()
]) ])
super(ChoiceField, self).__init__(**kwargs) super(ChoiceField, self).__init__(**kwargs)
def to_internal_value(self, data): def to_internal_value(self, data):
try: try:
return self.choice_strings_to_values[str(data)] return self.choice_strings_to_values[six.text_type(data)]
except KeyError: except KeyError:
self.fail('invalid_choice', input=data) self.fail('invalid_choice', input=data)
def to_representation(self, value): def to_representation(self, value):
return self.choice_strings_to_values[str(value)] return self.choice_strings_to_values[six.text_type(value)]
class MultipleChoiceField(ChoiceField): class MultipleChoiceField(ChoiceField):
@ -864,7 +864,7 @@ class MultipleChoiceField(ChoiceField):
def to_representation(self, value): def to_representation(self, value):
return set([ return set([
self.choice_strings_to_values[str(item)] for item in value self.choice_strings_to_values[six.text_type(item)] for item in value
]) ])

View File

@ -3,6 +3,7 @@ Provides generic filtering backends that can be used to filter the results
returned by list views. returned by list views.
""" """
from __future__ import unicode_literals from __future__ import unicode_literals
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.db import models from django.db import models
from django.utils import six from django.utils import six
@ -97,7 +98,7 @@ class SearchFilter(BaseFilterBackend):
if not search_fields: if not search_fields:
return queryset return queryset
orm_lookups = [self.construct_search(str(search_field)) orm_lookups = [self.construct_search(six.text_type(search_field))
for search_field in search_fields] for search_field in search_fields]
for search_term in self.get_search_terms(request): for search_term in self.get_search_terms(request):

View File

@ -3,10 +3,11 @@ Generic views that provide commonly needed behaviour.
""" """
from __future__ import unicode_literals from __future__ import unicode_literals
from django.db.models.query import QuerySet
from django.core.paginator import Paginator, InvalidPage from django.core.paginator import Paginator, InvalidPage
from django.db.models.query import QuerySet
from django.http import Http404 from django.http import Http404
from django.shortcuts import get_object_or_404 as _get_object_or_404 from django.shortcuts import get_object_or_404 as _get_object_or_404
from django.utils import six
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from rest_framework import views, mixins from rest_framework import views, mixins
from rest_framework.settings import api_settings from rest_framework.settings import api_settings
@ -127,7 +128,7 @@ class GenericAPIView(views.APIView):
error_format = _('Invalid page (%(page_number)s): %(message)s') error_format = _('Invalid page (%(page_number)s): %(message)s')
raise Http404(error_format % { raise Http404(error_format % {
'page_number': page_number, 'page_number': page_number,
'message': str(exc) 'message': six.text_type(exc)
}) })
return page return page

View File

@ -5,6 +5,7 @@ They give us a generic way of being able to handle various media types
on the request, such as form content or json encoded data. on the request, such as form content or json encoded data.
""" """
from __future__ import unicode_literals from __future__ import unicode_literals
from django.conf import settings from django.conf import settings
from django.core.files.uploadhandler import StopFutureHandlers from django.core.files.uploadhandler import StopFutureHandlers
from django.http import QueryDict from django.http import QueryDict
@ -132,7 +133,7 @@ class MultiPartParser(BaseParser):
data, files = parser.parse() data, files = parser.parse()
return DataAndFiles(data, files) return DataAndFiles(data, files)
except MultiPartParserError as exc: except MultiPartParserError as exc:
raise ParseError('Multipart form parse error - %s' % str(exc)) raise ParseError('Multipart form parse error - %s' % six.text_type(exc))
class XMLParser(BaseParser): class XMLParser(BaseParser):

View File

@ -4,6 +4,7 @@ from rest_framework.reverse import reverse
from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch, Resolver404 from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch, Resolver404
from django.db.models.query import QuerySet from django.db.models.query import QuerySet
from django.utils import six
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
@ -49,7 +50,7 @@ class StringRelatedField(Field):
super(StringRelatedField, self).__init__(**kwargs) super(StringRelatedField, self).__init__(**kwargs)
def to_representation(self, value): def to_representation(self, value):
return str(value) return six.text_type(value)
class PrimaryKeyRelatedField(RelatedField): class PrimaryKeyRelatedField(RelatedField):

View File

@ -3,6 +3,7 @@ Provide reverse functions that return fully qualified URLs
""" """
from __future__ import unicode_literals from __future__ import unicode_literals
from django.core.urlresolvers import reverse as django_reverse from django.core.urlresolvers import reverse as django_reverse
from django.utils import six
from django.utils.functional import lazy from django.utils.functional import lazy
@ -20,4 +21,4 @@ def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra
return url return url
reverse_lazy = lazy(reverse, str) reverse_lazy = lazy(reverse, six.text_type)

View File

@ -2,8 +2,8 @@
Helper classes for parsers. Helper classes for parsers.
""" """
from __future__ import unicode_literals from __future__ import unicode_literals
from django.utils import timezone
from django.db.models.query import QuerySet from django.db.models.query import QuerySet
from django.utils import six, timezone
from django.utils.datastructures import SortedDict from django.utils.datastructures import SortedDict
from django.utils.functional import Promise from django.utils.functional import Promise
from rest_framework.compat import force_text from rest_framework.compat import force_text
@ -40,7 +40,7 @@ class JSONEncoder(json.JSONEncoder):
representation = representation[:12] representation = representation[:12]
return representation return representation
elif isinstance(obj, datetime.timedelta): elif isinstance(obj, datetime.timedelta):
return str(obj.total_seconds()) return six.text_type(obj.total_seconds())
elif isinstance(obj, decimal.Decimal): elif isinstance(obj, decimal.Decimal):
# Serializers will coerce decimals to strings by default. # Serializers will coerce decimals to strings by default.
return float(obj) return float(obj)
@ -72,7 +72,7 @@ else:
than the usual behaviour of sorting the keys. than the usual behaviour of sorting the keys.
""" """
def represent_decimal(self, data): def represent_decimal(self, data):
return self.represent_scalar('tag:yaml.org,2002:str', str(data)) return self.represent_scalar('tag:yaml.org,2002:str', six.text_type(data))
def represent_mapping(self, tag, mapping, flow_style=None): def represent_mapping(self, tag, mapping, flow_style=None):
value = [] value = []