pep8/pyflakes cleanup

This commit is contained in:
Tom Christie 2012-01-21 18:33:34 +00:00
parent a851294d05
commit dea4a45ec7
12 changed files with 41 additions and 124 deletions

View File

@ -9,7 +9,6 @@ The set of authentication methods which are used is then specified by setting th
from django.contrib.auth import authenticate
from djangorestframework.compat import CsrfViewMiddleware
from djangorestframework.utils import as_tuple
import base64
__all__ = (

View File

@ -68,7 +68,6 @@ class RequestMixin(object):
self._load_method_and_content_type()
return self._method
@property
def content_type(self):
"""
@ -82,7 +81,6 @@ class RequestMixin(object):
self._load_method_and_content_type()
return self._content_type
@property
def DATA(self):
"""
@ -95,7 +93,6 @@ class RequestMixin(object):
self._load_data_and_files()
return self._data
@property
def FILES(self):
"""
@ -107,7 +104,6 @@ class RequestMixin(object):
self._load_data_and_files()
return self._files
def _load_data_and_files(self):
"""
Parse the request content into self.DATA and self.FILES.
@ -118,7 +114,6 @@ class RequestMixin(object):
if not hasattr(self, '_data'):
(self._data, self._files) = self._parse(self._get_stream(), self._content_type)
def _load_method_and_content_type(self):
"""
Set the method and content_type, and then check if they've been overridden.
@ -127,7 +122,6 @@ class RequestMixin(object):
self._content_type = self.request.META.get('HTTP_CONTENT_TYPE', self.request.META.get('CONTENT_TYPE', ''))
self._perform_form_overloading()
def _get_stream(self):
"""
Returns an object that may be used to stream the request content.
@ -144,10 +138,9 @@ class RequestMixin(object):
if content_length == 0:
return None
elif hasattr(request, 'read'):
return request
return request
return StringIO(request.raw_post_data)
def _perform_form_overloading(self):
"""
If this is a form POST request, then we need to check if the method and content/content_type have been
@ -173,7 +166,6 @@ class RequestMixin(object):
stream = StringIO(self._data.pop(self._CONTENT_PARAM)[0])
(self._data, self._files) = self._parse(stream, self._content_type)
def _parse(self, stream, content_type):
"""
Parse the request content.
@ -194,7 +186,6 @@ class RequestMixin(object):
{'error': 'Unsupported media type in request \'%s\'.' %
content_type})
@property
def _parsed_media_types(self):
"""
@ -202,7 +193,6 @@ class RequestMixin(object):
"""
return [parser.media_type for parser in self.parsers]
@property
def _default_parser(self):
"""
@ -211,7 +201,6 @@ class RequestMixin(object):
return self.parsers[0]
########## ResponseMixin ##########
class ResponseMixin(object):
@ -233,7 +222,6 @@ class ResponseMixin(object):
Should be a tuple/list of classes as described in the :mod:`renderers` module.
"""
# TODO: wrap this behavior around dispatch(), ensuring it works
# out of the box with existing Django classes that use render_to_response.
def render(self, response):
@ -266,7 +254,6 @@ class ResponseMixin(object):
return resp
def _determine_renderer(self, request):
"""
Determines the appropriate renderer for the output, given the client's 'Accept' header,
@ -309,7 +296,6 @@ class ResponseMixin(object):
{'detail': 'Could not satisfy the client\'s Accept header',
'available_types': self._rendered_media_types})
@property
def _rendered_media_types(self):
"""
@ -353,7 +339,6 @@ class AuthMixin(object):
Should be a tuple/list of classes as described in the :mod:`permissions` module.
"""
@property
def user(self):
"""
@ -364,7 +349,6 @@ class AuthMixin(object):
self._user = self._authenticate()
return self._user
def _authenticate(self):
"""
Attempt to authenticate the request using each authentication class in turn.
@ -377,7 +361,6 @@ class AuthMixin(object):
return user
return AnonymousUser()
# TODO: wrap this behavior around dispatch()
def _check_permissions(self):
"""

View File

@ -115,6 +115,7 @@ if yaml:
else:
YAMLParser = None
class PlainTextParser(BaseParser):
"""
Plain text parser.
@ -194,11 +195,11 @@ class XMLParser(BaseParser):
def _xml_convert(self, element):
"""
convert the xml `element` into the corresponding python object
convert the xml `element` into the corresponding python object
"""
children = element.getchildren()
if len(children) == 0:
return self._type_convert(element.text)
else:
@ -206,14 +207,14 @@ class XMLParser(BaseParser):
if children[0].tag == "list-item":
data = []
for child in children:
data.append(self._xml_convert(child))
else:
data.append(self._xml_convert(child))
else:
data = {}
for child in children:
data[child.tag] = self._xml_convert(child)
return data
def _type_convert(self, value):
"""
Converts the value returned by the XMl parse into the equivalent
@ -223,7 +224,7 @@ class XMLParser(BaseParser):
return value
try:
return datetime.datetime.strptime(value,'%Y-%m-%d %H:%M:%S')
return datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
except ValueError:
pass
@ -240,11 +241,12 @@ class XMLParser(BaseParser):
return value
DEFAULT_PARSERS = ( JSONParser,
FormParser,
MultiPartParser,
XMLParser
)
DEFAULT_PARSERS = (
JSONParser,
FormParser,
MultiPartParser,
XMLParser
)
if YAMLParser:
DEFAULT_PARSERS += ( YAMLParser, )
DEFAULT_PARSERS += (YAMLParser,)

View File

@ -226,7 +226,6 @@ class DocumentingTemplateRenderer(BaseRenderer):
return content
def _get_form_instance(self, view, method):
"""
Get a form, possibly bound to either the input or output data.
@ -262,7 +261,6 @@ class DocumentingTemplateRenderer(BaseRenderer):
return form_instance
def _get_generic_content_form(self, view):
"""
Returns a form that allows for arbitrary content types to be tunneled via standard HTML forms
@ -298,7 +296,6 @@ class DocumentingTemplateRenderer(BaseRenderer):
# Okey doke, let's do it
return GenericContentForm(view)
def render(self, obj=None, media_type=None):
"""
Renders *obj* using the :attr:`template` set on the class.
@ -335,7 +332,7 @@ class DocumentingTemplateRenderer(BaseRenderer):
context = RequestContext(self.view.request, {
'content': content,
'view': self.view,
'request': self.view.request, # TODO: remove
'request': self.view.request, # TODO: remove
'response': self.view.response,
'description': description,
'name': name,
@ -398,12 +395,14 @@ class DocumentingPlainTextRenderer(DocumentingTemplateRenderer):
template = 'renderer.txt'
DEFAULT_RENDERERS = ( JSONRenderer,
JSONPRenderer,
DocumentingHTMLRenderer,
DocumentingXHTMLRenderer,
DocumentingPlainTextRenderer,
XMLRenderer )
DEFAULT_RENDERERS = (
JSONRenderer,
JSONPRenderer,
DocumentingHTMLRenderer,
DocumentingXHTMLRenderer,
DocumentingPlainTextRenderer,
XMLRenderer
)
if YAMLRenderer:
DEFAULT_RENDERERS += (YAMLRenderer,)

View File

@ -1,20 +1,11 @@
from django import forms
from django.core.urlresolvers import reverse, get_urlconf, get_resolver, NoReverseMatch
from django.db import models
from django.db.models.query import QuerySet
from django.db.models.fields.related import RelatedField
from django.utils.encoding import smart_unicode
from djangorestframework.response import ErrorResponse
from djangorestframework.serializer import Serializer, _SkipField
from djangorestframework.utils import as_tuple
import decimal
import inspect
import re
class BaseResource(Serializer):
"""
@ -82,11 +73,10 @@ class FormResource(Resource):
"""
Flag to check for unknown fields when validating a form. If set to false and
we receive request data that is not expected by the form it raises an
:exc:`response.ErrorResponse` with status code 400. If set to true, only
:exc:`response.ErrorResponse` with status code 400. If set to true, only
expected fields are validated.
"""
def validate_request(self, data, files=None):
"""
Given some content as input return some cleaned, validated content.
@ -101,7 +91,6 @@ class FormResource(Resource):
"""
return self._validate(data, files)
def _validate(self, data, files, allowed_extra_fields=(), fake_data=None):
"""
Wrapped by validate to hide the extra flags that are used in the implementation.
@ -187,7 +176,6 @@ class FormResource(Resource):
# Return HTTP 400 response (BAD REQUEST)
raise ErrorResponse(400, detail)
def get_form_class(self, method=None):
"""
Returns the form class used to validate this resource.
@ -209,7 +197,6 @@ class FormResource(Resource):
return form
def get_bound_form(self, data=None, files=None, method=None):
"""
Given some content return a Django form bound to that content.
@ -226,20 +213,6 @@ class FormResource(Resource):
return form()
#class _RegisterModelResource(type):
# """
# Auto register new ModelResource classes into ``_model_to_resource``
# """
# def __new__(cls, name, bases, dct):
# resource_cls = type.__new__(cls, name, bases, dct)
# model_cls = dct.get('model', None)
# if model_cls:
# _model_to_resource[model_cls] = resource_cls
# return resource_cls
class ModelResource(FormResource):
"""
Resource class that uses forms for validation and otherwise falls back to a model form if no form is set.
@ -282,7 +255,6 @@ class ModelResource(FormResource):
The list of fields to exclude. This is only used if :attr:`fields` is not set.
"""
include = ('url',)
"""
The list of extra fields to include. This is only used if :attr:`fields` is not set.
@ -298,7 +270,6 @@ class ModelResource(FormResource):
self.model = getattr(view, 'model', None) or self.model
def validate_request(self, data, files=None):
"""
Given some content as input return some cleaned, validated content.
@ -315,7 +286,6 @@ class ModelResource(FormResource):
"""
return self._validate(data, files, allowed_extra_fields=self._property_fields_set)
def get_bound_form(self, data=None, files=None, method=None):
"""
Given some content return a ``Form`` instance bound to that content.
@ -348,7 +318,6 @@ class ModelResource(FormResource):
return form()
def url(self, instance):
"""
Attempts to reverse resolve the url of the given model *instance* for this resource.
@ -390,7 +359,6 @@ class ModelResource(FormResource):
pass
raise _SkipField
@property
def _model_fields_set(self):
"""

View File

@ -11,6 +11,7 @@ __all__ = ('Response', 'ErrorResponse')
# TODO: remove raw_content/cleaned_content and just use content?
class Response(object):
"""
An HttpResponse that may include content that hasn't yet been serialized.

View File

@ -3,10 +3,8 @@ Customizable serialization.
"""
from django.db import models
from django.db.models.query import QuerySet
from django.db.models.fields.related import RelatedField
from django.utils.encoding import smart_unicode, is_protected_type, smart_str
import decimal
import inspect
import types
@ -24,12 +22,14 @@ def _field_to_tuple(field):
return (field[0], field[1])
return (field, None)
def _fields_to_list(fields):
"""
Return a list of field names.
"""
return [_field_to_tuple(field)[0] for field in fields or ()]
def _fields_to_dict(fields):
"""
Return a `dict` of field name -> None, or tuple of fields, or Serializer class
@ -104,13 +104,11 @@ class Serializer(object):
The maximum depth to serialize to, or `None`.
"""
def __init__(self, depth=None, stack=[], **kwargs):
if depth is not None:
self.depth = depth
self.stack = stack
def get_fields(self, obj):
"""
Return the set of field names/keys to use for a model instance/dict.
@ -130,7 +128,6 @@ class Serializer(object):
return fields
def get_default_fields(self, obj):
"""
Return the default list of field names/keys for a model instance/dict.
@ -142,7 +139,6 @@ class Serializer(object):
else:
return obj.keys()
def get_related_serializer(self, key):
info = _fields_to_dict(self.fields).get(key, None)
@ -172,7 +168,6 @@ class Serializer(object):
# Otherwise use `related_serializer` or fall back to `Serializer`
return getattr(self, 'related_serializer') or Serializer
def serialize_key(self, key):
"""
Keys serialize to their string value,
@ -180,7 +175,6 @@ class Serializer(object):
"""
return self.rename.get(smart_str(key), smart_str(key))
def serialize_val(self, key, obj):
"""
Convert a model field or dict value into a serializable representation.
@ -202,7 +196,6 @@ class Serializer(object):
return related_serializer(depth=depth, stack=stack).serialize(obj)
def serialize_max_depth(self, obj):
"""
Determine how objects should be serialized once `depth` is exceeded.
@ -210,7 +203,6 @@ class Serializer(object):
"""
raise _SkipField
def serialize_recursion(self, obj):
"""
Determine how objects should be serialized if recursion occurs.
@ -218,7 +210,6 @@ class Serializer(object):
"""
raise _SkipField
def serialize_model(self, instance):
"""
Given a model instance or dict, serialize it to a dict..
@ -253,35 +244,30 @@ class Serializer(object):
return data
def serialize_iter(self, obj):
"""
Convert iterables into a serializable representation.
"""
return [self.serialize(item) for item in obj]
def serialize_func(self, obj):
"""
Convert no-arg methods and functions into a serializable representation.
"""
return self.serialize(obj())
def serialize_manager(self, obj):
"""
Convert a model manager into a serializable representation.
"""
return self.serialize_iter(obj.all())
def serialize_fallback(self, obj):
"""
Convert any unhandled object into a serializable representation.
"""
return smart_unicode(obj, strings_only=True)
def serialize(self, obj):
"""
Convert any object into a serializable representation.

View File

@ -1,6 +1,7 @@
from django.core.urlresolvers import resolve
from djangorestframework.utils.description import get_name
def get_breadcrumbs(url):
"""Given a url returns a list of breadcrumbs, which are each a tuple of (name, url)."""

View File

@ -50,7 +50,6 @@ def get_name(view):
return re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', ' \\1', name).strip()
def get_description(view):
"""
Provide a description for the view.
@ -63,7 +62,6 @@ def get_description(view):
if getattr(view, 'cls_instance', None):
view = view.cls_instance
# If this view has a resource that's been overridden, then use the resource's doctring
if getattr(view, 'resource', None) not in (None, Resource, FormResource, ModelResource):
doc = view.resource.__doc__
@ -88,4 +86,3 @@ def get_description(view):
# otherwise return it as-is
return doc

View File

@ -61,10 +61,10 @@ def order_by_precedence(media_type_lst):
1. 'type/*'
0. '*/*'
"""
ret = [[],[],[],[]]
ret = [[], [], [], []]
for media_type in media_type_lst:
precedence = _MediaType(media_type).precedence
ret[3-precedence].append(media_type)
ret[3 - precedence].append(media_type)
return ret
@ -103,29 +103,6 @@ class _MediaType(object):
return 2
return 3
#def quality(self):
# """
# Return a quality level for the media type.
# """
# try:
# return Decimal(self.params.get('q', '1.0'))
# except Exception:
# return Decimal(0)
#def score(self):
# """
# Return an overall score for a given media type given it's quality and precedence.
# """
# # NB. quality values should only have up to 3 decimal points
# # http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.9
# return self.quality * 10000 + self.precedence
#def as_tuple(self):
# return (self.main_type, self.sub_type, self.params)
#def __repr__(self):
# return "<MediaType %s>" % (self.as_tuple(),)
def __str__(self):
return unicode(self).encode('utf-8')
@ -134,4 +111,3 @@ class _MediaType(object):
for key, val in self.params.items():
ret += "; %s=%s" % (key, val)
return ret

View File

@ -5,13 +5,16 @@ from django.shortcuts import render_to_response
from django.template import RequestContext
import base64
def deny_robots(request):
return HttpResponse('User-agent: *\nDisallow: /', mimetype='text/plain')
def favicon(request):
data = 'AAABAAEAEREAAAEAIADwBAAAFgAAACgAAAARAAAAIgAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADLy8tLy8vL3svLy1QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAy8vLBsvLywkAAAAATkZFS1xUVPqhn57/y8vL0gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJmVlQ/GxcXiy8vL88vLy4FdVlXzTkZF/2RdXP/Ly8vty8vLtMvLy5DLy8vty8vLxgAAAAAAAAAAAAAAAAAAAABORkUJTkZF4lNMS/+Lh4f/cWtq/05GRf9ORkX/Vk9O/3JtbP+Ef3//Vk9O/2ljYv/Ly8v5y8vLCQAAAAAAAAAAAAAAAE5GRQlORkX2TkZF/05GRf9ORkX/TkZF/05GRf9ORkX/TkZF/05GRf9ORkX/UElI/8PDw5cAAAAAAAAAAAAAAAAAAAAAAAAAAE5GRZZORkX/TkZF/05GRf9ORkX/TkZF/05GRf9ORkX/TkZF/05GR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GH
# Replicate django.contrib.auth.views.login simply so we don't have get users to update TEMPLATE_CONTEXT_PROCESSORS
# to add ADMIN_MEDIA_PREFIX to the RequestContext. I don't like this but really really want users to not have to

View File

@ -25,7 +25,6 @@ __all__ = (
)
class View(ResourceMixin, RequestMixin, ResponseMixin, AuthMixin, DjangoView):
"""
Handles incoming requests and maps them to REST operations.
@ -48,13 +47,13 @@ class View(ResourceMixin, RequestMixin, ResponseMixin, AuthMixin, DjangoView):
List of parsers the resource can parse the request with.
"""
authentication = ( authentication.UserLoggedInAuthentication,
authentication.BasicAuthentication )
authentication = (authentication.UserLoggedInAuthentication,
authentication.BasicAuthentication)
"""
List of all authenticating methods to attempt.
"""
permissions = ( permissions.FullAnonAccess, )
permissions = (permissions.FullAnonAccess,)
"""
List of all permissions that must be checked.
"""
@ -185,18 +184,21 @@ class ModelView(View):
"""
resource = resources.ModelResource
class InstanceModelView(InstanceMixin, ReadModelMixin, UpdateModelMixin, DeleteModelMixin, ModelView):
"""
A view which provides default operations for read/update/delete against a model instance.
"""
_suffix = 'Instance'
class ListModelView(ListModelMixin, ModelView):
"""
A view which provides default operations for list, against a model in the database.
"""
_suffix = 'List'
class ListOrCreateModelView(ListModelMixin, CreateModelMixin, ModelView):
"""
A view which provides default operations for list and create, against a model in the database.