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
from __future__ import unicode_literals
import django
import inspect
from django.core.exceptions import ImproperlyConfigured
from django.conf import settings
from django.utils import six
import django
import inspect
# Handle django.utils.encoding rename in 1.5 onwards.
@ -177,12 +178,12 @@ class RequestFactory(DjangoRequestFactory):
r = {
'PATH_INFO': self._get_path(parsed),
'QUERY_STRING': force_text(parsed[4]),
'REQUEST_METHOD': str(method),
'REQUEST_METHOD': six.text_type(method),
}
if data:
r.update({
'CONTENT_LENGTH': len(data),
'CONTENT_TYPE': str(content_type),
'CONTENT_TYPE': six.text_type(content_type),
'wsgi.input': FakePayload(data),
})
elif django.VERSION <= (1, 4):

View File

@ -2,7 +2,7 @@ from django import forms
from django.conf import settings
from django.core import validators
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.dateparse import parse_date, parse_datetime, parse_time
from django.utils.encoding import is_protected_type
@ -431,10 +431,10 @@ class CharField(Field):
return super(CharField, self).run_validation(data)
def to_internal_value(self, data):
return str(data)
return six.text_type(data)
def to_representation(self, value):
return str(value)
return six.text_type(value)
class EmailField(CharField):
@ -448,10 +448,10 @@ class EmailField(CharField):
self.validators.append(validator)
def to_internal_value(self, data):
return str(data).strip()
return six.text_type(data).strip()
def to_representation(self, value):
return str(value).strip()
return six.text_type(value).strip()
class RegexField(CharField):
@ -510,7 +510,7 @@ class IntegerField(Field):
def to_internal_value(self, data):
try:
data = int(str(data))
data = int(six.text_type(data))
except (ValueError, TypeError):
self.fail('invalid')
return data
@ -616,7 +616,7 @@ class DecimalField(Field):
def to_representation(self, value):
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.prec = self.max_digits
@ -832,19 +832,19 @@ class ChoiceField(Field):
# Allows us to deal with eg. integer choices while supporting either
# integer or string input, but still get the correct datatype out.
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)
def to_internal_value(self, data):
try:
return self.choice_strings_to_values[str(data)]
return self.choice_strings_to_values[six.text_type(data)]
except KeyError:
self.fail('invalid_choice', input=data)
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):
@ -864,7 +864,7 @@ class MultipleChoiceField(ChoiceField):
def to_representation(self, value):
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.
"""
from __future__ import unicode_literals
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.utils import six
@ -97,7 +98,7 @@ class SearchFilter(BaseFilterBackend):
if not search_fields:
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_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 django.db.models.query import QuerySet
from django.core.paginator import Paginator, InvalidPage
from django.db.models.query import QuerySet
from django.http import Http404
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 rest_framework import views, mixins
from rest_framework.settings import api_settings
@ -127,7 +128,7 @@ class GenericAPIView(views.APIView):
error_format = _('Invalid page (%(page_number)s): %(message)s')
raise Http404(error_format % {
'page_number': page_number,
'message': str(exc)
'message': six.text_type(exc)
})
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.
"""
from __future__ import unicode_literals
from django.conf import settings
from django.core.files.uploadhandler import StopFutureHandlers
from django.http import QueryDict
@ -132,7 +133,7 @@ class MultiPartParser(BaseParser):
data, files = parser.parse()
return DataAndFiles(data, files)
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):

View File

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

View File

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

View File

@ -2,8 +2,8 @@
Helper classes for parsers.
"""
from __future__ import unicode_literals
from django.utils import timezone
from django.db.models.query import QuerySet
from django.utils import six, timezone
from django.utils.datastructures import SortedDict
from django.utils.functional import Promise
from rest_framework.compat import force_text
@ -40,7 +40,7 @@ class JSONEncoder(json.JSONEncoder):
representation = representation[:12]
return representation
elif isinstance(obj, datetime.timedelta):
return str(obj.total_seconds())
return six.text_type(obj.total_seconds())
elif isinstance(obj, decimal.Decimal):
# Serializers will coerce decimals to strings by default.
return float(obj)
@ -72,7 +72,7 @@ else:
than the usual behaviour of sorting the keys.
"""
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):
value = []