Resolve linting issues

This commit is contained in:
Tom Christie 2014-08-19 13:54:52 +01:00
parent 19f3134062
commit d2795dd26d
10 changed files with 42 additions and 48 deletions

View File

@ -63,8 +63,10 @@ def get_component(obj, attr_name):
def readable_datetime_formats(formats): def readable_datetime_formats(formats):
format = ', '.join(formats).replace(ISO_8601, format = ', '.join(formats).replace(
'YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]') ISO_8601,
'YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'
)
return humanize_strptime(format) return humanize_strptime(format)
@ -425,7 +427,7 @@ class ModelField(WritableField):
} }
##### Typed Fields ##### # Typed Fields
class BooleanField(WritableField): class BooleanField(WritableField):
type_name = 'BooleanField' type_name = 'BooleanField'
@ -484,7 +486,7 @@ class URLField(CharField):
type_label = 'url' type_label = 'url'
def __init__(self, **kwargs): def __init__(self, **kwargs):
if not 'validators' in kwargs: if 'validators' not in kwargs:
kwargs['validators'] = [validators.URLValidator()] kwargs['validators'] = [validators.URLValidator()]
super(URLField, self).__init__(**kwargs) super(URLField, self).__init__(**kwargs)

View File

@ -210,9 +210,8 @@ class GenericAPIView(views.APIView):
return filter_backends return filter_backends
######################## # The following methods provide default implementations
### The following methods provide default implementations # that you may want to override for more complex cases.
### that you may want to override for more complex cases.
def get_paginate_by(self, queryset=None): def get_paginate_by(self, queryset=None):
""" """
@ -340,12 +339,11 @@ class GenericAPIView(views.APIView):
return obj return obj
######################## # The following are placeholder methods,
### The following are placeholder methods, # and are intended to be overridden.
### and are intended to be overridden. #
### # The are not called by GenericAPIView directly,
### The are not called by GenericAPIView directly, # but are used by the mixin methods.
### but are used by the mixin methods.
def pre_save(self, obj): def pre_save(self, obj):
""" """
@ -417,10 +415,8 @@ class GenericAPIView(views.APIView):
return ret return ret
########################################################## # Concrete view classes that provide method handlers
### Concrete view classes that provide method handlers ### # by composing the mixin classes with the base view.
### by composing the mixin classes with the base view. ###
##########################################################
class CreateAPIView(mixins.CreateModelMixin, class CreateAPIView(mixins.CreateModelMixin,
GenericAPIView): GenericAPIView):
@ -535,9 +531,7 @@ class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin,
return self.destroy(request, *args, **kwargs) return self.destroy(request, *args, **kwargs)
########################## # Deprecated classes
### Deprecated classes ###
##########################
class MultipleObjectAPIView(GenericAPIView): class MultipleObjectAPIView(GenericAPIView):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):

View File

@ -19,8 +19,7 @@ from rest_framework.compat import smart_text
import warnings import warnings
##### Relational fields ##### # Relational fields
# Not actually Writable, but subclasses may need to be. # Not actually Writable, but subclasses may need to be.
class RelatedField(WritableField): class RelatedField(WritableField):
@ -66,7 +65,7 @@ class RelatedField(WritableField):
else: # Reverse else: # Reverse
self.queryset = manager.field.rel.to._default_manager.all() self.queryset = manager.field.rel.to._default_manager.all()
### We need this stuff to make form choices work... # We need this stuff to make form choices work...
def prepare_value(self, obj): def prepare_value(self, obj):
return self.to_native(obj) return self.to_native(obj)
@ -113,7 +112,7 @@ class RelatedField(WritableField):
choices = property(_get_choices, _set_choices) choices = property(_get_choices, _set_choices)
### Default value handling # Default value handling
def get_default_value(self): def get_default_value(self):
default = super(RelatedField, self).get_default_value() default = super(RelatedField, self).get_default_value()
@ -121,7 +120,7 @@ class RelatedField(WritableField):
return [] return []
return default return default
### Regular serializer stuff... # Regular serializer stuff...
def field_to_native(self, obj, field_name): def field_to_native(self, obj, field_name):
try: try:
@ -181,7 +180,7 @@ class RelatedField(WritableField):
into[(self.source or field_name)] = self.from_native(value) into[(self.source or field_name)] = self.from_native(value)
### PrimaryKey relationships # PrimaryKey relationships
class PrimaryKeyRelatedField(RelatedField): class PrimaryKeyRelatedField(RelatedField):
""" """
@ -269,8 +268,7 @@ class PrimaryKeyRelatedField(RelatedField):
return self.to_native(pk) return self.to_native(pk)
### Slug relationships # Slug relationships
class SlugRelatedField(RelatedField): class SlugRelatedField(RelatedField):
""" """
@ -305,7 +303,7 @@ class SlugRelatedField(RelatedField):
raise ValidationError(msg) raise ValidationError(msg)
### Hyperlinked relationships # Hyperlinked relationships
class HyperlinkedRelatedField(RelatedField): class HyperlinkedRelatedField(RelatedField):
""" """

View File

@ -414,7 +414,7 @@ class BrowsableAPIRenderer(BaseRenderer):
""" """
Returns True if a form should be shown for this method. Returns True if a form should be shown for this method.
""" """
if not method in view.allowed_methods: if method not in view.allowed_methods:
return # Not a valid method return # Not a valid method
if not api_settings.FORM_METHOD_OVERRIDE: if not api_settings.FORM_METHOD_OVERRIDE:

View File

@ -403,7 +403,7 @@ class Request(object):
self._not_authenticated() self._not_authenticated()
raise raise
if not user_auth_tuple is None: if user_auth_tuple is not None:
self._authenticator = authenticator self._authenticator = authenticator
self._user, self._auth = user_auth_tuple self._user, self._auth = user_auth_tuple
return return

View File

@ -166,7 +166,7 @@ def urlize_quoted_links(text, trim_url_limit=None, nofollow=True, autoescape=Tru
url = smart_urlquote_wrapper(middle) url = smart_urlquote_wrapper(middle)
elif simple_url_2_re.match(middle): elif simple_url_2_re.match(middle):
url = smart_urlquote_wrapper('http://%s' % middle) url = smart_urlquote_wrapper('http://%s' % middle)
elif not ':' in middle and simple_email_re.match(middle): elif ':' not in middle and simple_email_re.match(middle):
local, domain = middle.rsplit('@', 1) local, domain = middle.rsplit('@', 1)
try: try:
domain = domain.encode('idna').decode('ascii') domain = domain.encode('idna').decode('ascii')

View File

@ -47,8 +47,8 @@ def pytest_configure():
) )
try: try:
import oauth_provider import oauth_provider # NOQA
import oauth2 import oauth2 # NOQA
except ImportError: except ImportError:
pass pass
else: else:
@ -57,7 +57,7 @@ def pytest_configure():
) )
try: try:
import provider import provider # NOQA
except ImportError: except ImportError:
pass pass
else: else:
@ -68,13 +68,13 @@ def pytest_configure():
# guardian is optional # guardian is optional
try: try:
import guardian import guardian # NOQA
except ImportError: except ImportError:
pass pass
else: else:
settings.ANONYMOUS_USER_ID = -1 settings.ANONYMOUS_USER_ID = -1
settings.AUTHENTICATION_BACKENDS = ( settings.AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend', # default 'django.contrib.auth.backends.ModelBackend',
'guardian.backends.ObjectPermissionBackend', 'guardian.backends.ObjectPermissionBackend',
) )
settings.INSTALLED_APPS += ( settings.INSTALLED_APPS += (

View File

@ -363,11 +363,11 @@ class TestMaxPaginateByParam(TestCase):
self.assertEqual(response.data['results'], self.data[:3]) self.assertEqual(response.data['results'], self.data[:3])
### Tests for context in pagination serializers # Tests for context in pagination serializers
class CustomField(serializers.Field): class CustomField(serializers.Field):
def to_native(self, value): def to_native(self, value):
if not 'view' in self.context: if 'view' not in self.context:
raise RuntimeError("context isn't getting passed into custom field") raise RuntimeError("context isn't getting passed into custom field")
return "value" return "value"
@ -377,7 +377,7 @@ class BasicModelSerializer(serializers.Serializer):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(BasicModelSerializer, self).__init__(*args, **kwargs) super(BasicModelSerializer, self).__init__(*args, **kwargs)
if not 'view' in self.context: if 'view' not in self.context:
raise RuntimeError("context isn't getting passed into serializer init") raise RuntimeError("context isn't getting passed into serializer init")
@ -398,7 +398,7 @@ class TestContextPassedToCustomField(TestCase):
self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.status_code, status.HTTP_200_OK)
### Tests for custom pagination serializers # Tests for custom pagination serializers
class LinksSerializer(serializers.Serializer): class LinksSerializer(serializers.Serializer):
next = pagination.NextPageField(source='*') next = pagination.NextPageField(source='*')

View File

@ -415,7 +415,7 @@ class ValidationTests(TestCase):
mistaken for not having a default.""" mistaken for not having a default."""
data = { data = {
'title': 'Some action item', 'title': 'Some action item',
#No 'done' value. # No 'done' value.
} }
serializer = ActionItemSerializer(self.actionitem, data=data) serializer = ActionItemSerializer(self.actionitem, data=data)
self.assertEqual(serializer.is_valid(), True) self.assertEqual(serializer.is_valid(), True)
@ -1282,7 +1282,7 @@ class BlankFieldTests(TestCase):
self.fail('Exception raised on save() after validation passes') self.fail('Exception raised on save() after validation passes')
#test for issue #460 # Test for issue #460
class SerializerPickleTests(TestCase): class SerializerPickleTests(TestCase):
""" """
Test pickleability of the output of Serializers Test pickleability of the output of Serializers
@ -1506,7 +1506,7 @@ class NestedSerializerContextTests(TestCase):
callable = serializers.SerializerMethodField('_callable') callable = serializers.SerializerMethodField('_callable')
def _callable(self, instance): def _callable(self, instance):
if not 'context_item' in self.context: if 'context_item' not in self.context:
raise RuntimeError("context isn't getting passed into 2nd level nested serializer") raise RuntimeError("context isn't getting passed into 2nd level nested serializer")
return "success" return "success"
@ -1519,7 +1519,7 @@ class NestedSerializerContextTests(TestCase):
callable = serializers.SerializerMethodField("_callable") callable = serializers.SerializerMethodField("_callable")
def _callable(self, instance): def _callable(self, instance):
if not 'context_item' in self.context: if 'context_item' not in self.context:
raise RuntimeError("context isn't getting passed into 1st level nested serializer") raise RuntimeError("context isn't getting passed into 1st level nested serializer")
return "success" return "success"
@ -1822,7 +1822,7 @@ class MetadataSerializerTestCase(TestCase):
self.assertEqual(expected, metadata) self.assertEqual(expected, metadata)
### Regression test for #840 # Regression test for #840
class SimpleModel(models.Model): class SimpleModel(models.Model):
text = models.CharField(max_length=100) text = models.CharField(max_length=100)
@ -1856,7 +1856,7 @@ class FieldValidationRemovingAttr(TestCase):
self.assertEqual(serializer.object.text, 'foo') self.assertEqual(serializer.object.text, 'foo')
### Regression test for #878 # Regression test for #878
class SimpleTargetModel(models.Model): class SimpleTargetModel(models.Model):
text = models.CharField(max_length=100) text = models.CharField(max_length=100)

View File

@ -11,7 +11,7 @@ class TemplateTagTests(TestCase):
def test_add_query_param_with_non_latin_charactor(self): def test_add_query_param_with_non_latin_charactor(self):
# Ensure we don't double-escape non-latin characters # Ensure we don't double-escape non-latin characters
# that are present in the querystring. # that are present in the querystring.
# See #1314. # See #1314.
request = factory.get("/", {'q': '查询'}) request = factory.get("/", {'q': '查询'})
json_url = add_query_param(request, "format", "json") json_url = add_query_param(request, "format", "json")