Skip to content

Commit

Permalink
First passing test under p3k \o/
Browse files Browse the repository at this point in the history
  • Loading branch information
xordoquy committed Nov 21, 2012
1 parent ab3c472 commit b3698ac
Show file tree
Hide file tree
Showing 20 changed files with 162 additions and 114 deletions.
10 changes: 7 additions & 3 deletions rest_framework/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
"""

from django.contrib.auth import authenticate
from django.utils.encoding import smart_unicode, DjangoUnicodeDecodeError
from django.utils.encoding import DjangoUnicodeDecodeError
try:
from django.utils.encoding import smart_text
except ImportError:
from django.utils.encoding import smart_unicode as smart_text
from rest_framework import exceptions
from rest_framework.compat import CsrfViewMiddleware
from rest_framework.authtoken.models import Token
Expand Down Expand Up @@ -41,8 +45,8 @@ def authenticate(self, request):
return None

try:
userid = smart_unicode(auth_parts[0])
password = smart_unicode(auth_parts[2])
userid = smart_text(auth_parts[0])
password = smart_text(auth_parts[2])
except DjangoUnicodeDecodeError:
return None

Expand Down
16 changes: 10 additions & 6 deletions rest_framework/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
versions of django/python, and compatibility wrappers around optional packages.
"""
# flake8: noqa
from __future__ import unicode_literals
import six

import django

# django-filter is optional
Expand All @@ -16,7 +19,7 @@
try:
import cStringIO as StringIO
except ImportError:
import StringIO
from six import StringIO


def get_concrete_model(model_cls):
Expand All @@ -38,7 +41,7 @@ def get_concrete_model(model_cls):
try:
from django.contrib.auth.models import User
except ImportError:
raise ImportError(u"User model is not to be found.")
raise ImportError("User model is not to be found.")


# First implementation of Django class-based views did not include head method
Expand All @@ -59,11 +62,11 @@ def as_view(cls, **initkwargs):
# sanitize keyword arguments
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError(u"You tried to pass in the %s method name as a "
u"keyword argument to %s(). Don't do that."
raise TypeError("You tried to pass in the %s method name as a "
"keyword argument to %s(). Don't do that."
% (key, cls.__name__))
if not hasattr(cls, key):
raise TypeError(u"%s() received an invalid keyword %r" % (
raise TypeError("%s() received an invalid keyword %r" % (
cls.__name__, key))

def view(request, *args, **kwargs):
Expand Down Expand Up @@ -130,7 +133,8 @@ def constant_time_compare(val1, val2):
randrange = random.SystemRandom().randrange
else:
randrange = random.randrange
_MAX_CSRF_KEY = 18446744073709551616L # 2 << 63

_MAX_CSRF_KEY = 18446744073709551616 # 2 << 63

REASON_NO_REFERER = "Referer checking failed - no Referer."
REASON_BAD_REFERER = "Referer checking failed - %s does not match %s."
Expand Down
73 changes: 42 additions & 31 deletions rest_framework/fields.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@

from __future__ import unicode_literals
import six

import copy
import datetime
import inspect
Expand All @@ -12,12 +16,19 @@
from django.conf import settings
from django.forms import widgets
from django.forms.models import ModelChoiceIterator
from django.utils.encoding import is_protected_type, smart_unicode
from django.utils.encoding import is_protected_type
try:
from django.utils.encoding import smart_text
except ImportError:
from django.utils.encoding import smart_unicode as smart_text
from django.utils.translation import ugettext_lazy as _
from rest_framework.reverse import reverse
from rest_framework.compat import parse_date, parse_datetime
from rest_framework.compat import timezone
from urlparse import urlparse
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse


def is_simple_callable(obj):
Expand Down Expand Up @@ -92,11 +103,11 @@ def to_native(self, value):

if is_protected_type(value):
return value
elif hasattr(value, '__iter__') and not isinstance(value, (dict, basestring)):
elif hasattr(value, '__iter__') and not isinstance(value, (dict, six.string_types)):
return [self.to_native(item) for item in value]
elif isinstance(value, dict):
return dict(map(self.to_native, (k, v)) for k, v in value.items())
return smart_unicode(value)
return smart_text(value)

def attributes(self):
"""
Expand Down Expand Up @@ -297,8 +308,8 @@ def label_from_instance(self, obj):
"""
Return a readable representation for use with eg. select widgets.
"""
desc = smart_unicode(obj)
ident = smart_unicode(self.to_native(obj))
desc = smart_text(obj)
ident = smart_text(self.to_native(obj))
if desc == ident:
return desc
return "%s - %s" % (desc, ident)
Expand Down Expand Up @@ -401,8 +412,8 @@ def label_from_instance(self, obj):
"""
Return a readable representation for use with eg. select widgets.
"""
desc = smart_unicode(obj)
ident = smart_unicode(self.to_native(obj.pk))
desc = smart_text(obj)
ident = smart_text(self.to_native(obj.pk))
if desc == ident:
return desc
return "%s - %s" % (desc, ident)
Expand All @@ -418,7 +429,7 @@ def from_native(self, data):
try:
return self.queryset.get(pk=data)
except ObjectDoesNotExist:
msg = "Invalid pk '%s' - object does not exist." % smart_unicode(data)
msg = "Invalid pk '%s' - object does not exist." % smart_text(data)
raise ValidationError(msg)

def field_to_native(self, obj, field_name):
Expand Down Expand Up @@ -446,8 +457,8 @@ def label_from_instance(self, obj):
"""
Return a readable representation for use with eg. select widgets.
"""
desc = smart_unicode(obj)
ident = smart_unicode(self.to_native(obj.pk))
desc = smart_text(obj)
ident = smart_text(self.to_native(obj.pk))
if desc == ident:
return desc
return "%s - %s" % (desc, ident)
Expand All @@ -473,7 +484,7 @@ def from_native(self, data):
try:
return self.queryset.get(pk=data)
except ObjectDoesNotExist:
msg = "Invalid pk '%s' - object does not exist." % smart_unicode(data)
msg = "Invalid pk '%s' - object does not exist." % smart_text(data)
raise ValidationError(msg)

### Slug relationships
Expand Down Expand Up @@ -674,7 +685,7 @@ class BooleanField(WritableField):
type_name = 'BooleanField'
widget = widgets.CheckboxInput
default_error_messages = {
'invalid': _(u"'%s' value must be either True or False."),
'invalid': _("'%s' value must be either True or False."),
}
empty = False

Expand Down Expand Up @@ -713,9 +724,9 @@ def validate(self, value):
super(CharField, self).validate(value)

def from_native(self, value):
if isinstance(value, basestring) or value is None:
if isinstance(value, six.string_types) or value is None:
return value
return smart_unicode(value)
return smart_text(value)


class URLField(CharField):
Expand Down Expand Up @@ -773,10 +784,10 @@ def valid_value(self, value):
if isinstance(v, (list, tuple)):
# This is an optgroup, so look inside the group for options
for k2, v2 in v:
if value == smart_unicode(k2):
if value == smart_text(k2):
return True
else:
if value == smart_unicode(k):
if value == smart_text(k):
return True
return False

Expand Down Expand Up @@ -814,7 +825,7 @@ def _get_regex(self):
return self._regex

def _set_regex(self, regex):
if isinstance(regex, basestring):
if isinstance(regex, six.string_types):
regex = re.compile(regex)
self._regex = regex
if hasattr(self, '_regex_validator') and self._regex_validator in self.validators:
Expand All @@ -835,10 +846,10 @@ class DateField(WritableField):
type_name = 'DateField'

default_error_messages = {
'invalid': _(u"'%s' value has an invalid date format. It must be "
u"in YYYY-MM-DD format."),
'invalid_date': _(u"'%s' value has the correct format (YYYY-MM-DD) "
u"but it is an invalid date."),
'invalid': _("'%s' value has an invalid date format. It must be "
"in YYYY-MM-DD format."),
'invalid_date': _("'%s' value has the correct format (YYYY-MM-DD) "
"but it is an invalid date."),
}
empty = None

Expand Down Expand Up @@ -872,13 +883,13 @@ class DateTimeField(WritableField):
type_name = 'DateTimeField'

default_error_messages = {
'invalid': _(u"'%s' value has an invalid format. It must be in "
u"YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."),
'invalid_date': _(u"'%s' value has the correct format "
u"(YYYY-MM-DD) but it is an invalid date."),
'invalid_datetime': _(u"'%s' value has the correct format "
u"(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
u"but it is an invalid date/time."),
'invalid': _("'%s' value has an invalid format. It must be in "
"YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."),
'invalid_date': _("'%s' value has the correct format "
"(YYYY-MM-DD) but it is an invalid date."),
'invalid_datetime': _("'%s' value has the correct format "
"(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
"but it is an invalid date/time."),
}
empty = None

Expand All @@ -895,8 +906,8 @@ def from_native(self, value):
# local time. This won't work during DST change, but we can't
# do much about it, so we let the exceptions percolate up the
# call stack.
warnings.warn(u"DateTimeField received a naive datetime (%s)"
u" while time zone support is active." % value,
warnings.warn("DateTimeField received a naive datetime (%s)"
" while time zone support is active." % value,
RuntimeWarning)
default_timezone = timezone.get_default_timezone()
value = timezone.make_aware(value, default_timezone)
Expand Down
4 changes: 3 additions & 1 deletion rest_framework/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
We don't bind behaviour to http method handlers yet,
which allows mixin classes to be composed in interesting ways.
"""
from __future__ import unicode_literals

from django.http import Http404
from rest_framework import status
from rest_framework.response import Response
Expand Down Expand Up @@ -38,7 +40,7 @@ class ListModelMixin(object):
List a queryset.
Should be mixed in with `MultipleObjectAPIView`.
"""
empty_error = u"Empty list and '%(class_name)s.allow_empty' is False."
empty_error = "Empty list and '%(class_name)s.allow_empty' is False."

def list(self, request, *args, **kwargs):
queryset = self.get_queryset()
Expand Down
8 changes: 4 additions & 4 deletions rest_framework/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def parse(self, stream, media_type=None, parser_context=None):
"""
try:
return json.load(stream)
except ValueError, exc:
except ValueError as exc:
raise ParseError('JSON parse error - %s' % unicode(exc))


Expand All @@ -76,7 +76,7 @@ def parse(self, stream, media_type=None, parser_context=None):
"""
try:
return yaml.safe_load(stream)
except (ValueError, yaml.parser.ParserError), exc:
except (ValueError, yaml.parser.ParserError) as exc:
raise ParseError('YAML parse error - %s' % unicode(exc))


Expand Down Expand Up @@ -121,7 +121,7 @@ def parse(self, stream, media_type=None, parser_context=None):
parser = DjangoMultiPartParser(meta, stream, upload_handlers)
data, files = parser.parse()
return DataAndFiles(data, files)
except MultiPartParserError, exc:
except MultiPartParserError as exc:
raise ParseError('Multipart form parse error - %s' % unicode(exc))


Expand All @@ -135,7 +135,7 @@ class XMLParser(BaseParser):
def parse(self, stream, media_type=None, parser_context=None):
try:
tree = ET.parse(stream)
except (ExpatError, ETParseError, ValueError), exc:
except (ExpatError, ETParseError, ValueError) as exc:
raise ParseError('XML parse error - %s' % unicode(exc))
data = self._xml_convert(tree.getroot())

Expand Down
6 changes: 4 additions & 2 deletions rest_framework/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
REST framework also provides an HTML renderer the renders the browsable API.
"""
from __future__ import unicode_literals

import copy
import string
from django import forms
Expand Down Expand Up @@ -60,7 +62,7 @@ def render(self, data, accepted_media_type=None, renderer_context=None):
if accepted_media_type:
# If the media type looks like 'application/json; indent=4',
# then pretty print the result.
base_media_type, params = parse_header(accepted_media_type)
base_media_type, params = parse_header(accepted_media_type.encode('ascii'))
indent = params.get('indent', indent)
try:
indent = max(min(int(indent), 8), 0)
Expand Down Expand Up @@ -100,7 +102,7 @@ def render(self, data, accepted_media_type=None, renderer_context=None):
callback = self.get_callback(renderer_context)
json = super(JSONPRenderer, self).render(data, accepted_media_type,
renderer_context)
return u"%s(%s);" % (callback, json)
return "%s(%s);" % (callback, json)


class XMLRenderer(BaseRenderer):
Expand Down
2 changes: 1 addition & 1 deletion rest_framework/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
- full support of PUT method, including support for file uploads
- form overloading of HTTP method, content type and content
"""
from StringIO import StringIO
from rest_framework.compat import StringIO

from django.http.multipartparser import parse_header
from rest_framework import exceptions
Expand Down
4 changes: 3 additions & 1 deletion rest_framework/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
"""
from django.conf import settings
from django.utils import importlib
from six import string_types



USER_SETTINGS = getattr(settings, 'REST_FRAMEWORK', None)
Expand Down Expand Up @@ -98,7 +100,7 @@ def perform_import(val, setting_name):
If the given setting is a string import notation,
then perform the necessary import or imports.
"""
if isinstance(val, basestring):
if isinstance(val, string_types):
return import_from_string(val, setting_name)
elif isinstance(val, (list, tuple)):
return [import_from_string(item, setting_name) for item in val]
Expand Down
Loading

0 comments on commit b3698ac

Please sign in to comment.