django-rest-framework/rest_framework/generics.py

365 lines
12 KiB
Python
Raw Normal View History

"""
2012-10-30 03:30:52 +04:00
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.http import Http404
from django.shortcuts import get_object_or_404 as _get_object_or_404
from django.utils.translation import ugettext as _
2014-09-24 17:09:49 +04:00
from rest_framework import views, mixins
from rest_framework.settings import api_settings
def strict_positive_int(integer_string, cutoff=None):
"""
Cast a string to a strictly positive integer.
"""
ret = int(integer_string)
if ret <= 0:
raise ValueError()
if cutoff:
ret = min(ret, cutoff)
return ret
2014-08-19 16:28:07 +04:00
2013-10-04 18:49:56 +04:00
def get_object_or_404(queryset, *filter_args, **filter_kwargs):
"""
2014-09-05 19:29:46 +04:00
Same as Django's standard shortcut, but make sure to also raise 404
if the filter_kwargs don't match the required types.
"""
try:
2013-10-04 18:49:56 +04:00
return _get_object_or_404(queryset, *filter_args, **filter_kwargs)
except (TypeError, ValueError):
raise Http404
2012-10-25 16:50:39 +04:00
class GenericAPIView(views.APIView):
"""
Base class for all other generic views.
"""
2012-11-17 03:22:15 +04:00
2013-04-25 01:40:24 +04:00
# You'll need to either set these attributes,
2013-04-30 11:24:33 +04:00
# or override `get_queryset()`/`get_serializer_class()`.
# If you are overriding a view method, it is important that you call
# `get_queryset()` instead of accessing the `queryset` property directly,
# as `queryset` will get evaluated only once, and those results are cached
# for all subsequent requests.
queryset = None
serializer_class = None
2013-04-25 01:40:24 +04:00
# If you want to use object lookups other than pk, set this attribute.
2013-04-30 11:24:33 +04:00
# For more complex lookup requirements override `get_object()`.
2013-04-25 01:40:24 +04:00
lookup_field = 'pk'
2013-10-21 12:47:07 +04:00
lookup_url_kwarg = None
2013-04-23 14:59:13 +04:00
2013-04-25 01:40:24 +04:00
# Pagination settings
paginate_by = api_settings.PAGINATE_BY
paginate_by_param = api_settings.PAGINATE_BY_PARAM
2013-08-26 20:05:36 +04:00
max_paginate_by = api_settings.MAX_PAGINATE_BY
pagination_serializer_class = api_settings.DEFAULT_PAGINATION_SERIALIZER_CLASS
page_kwarg = 'page'
2013-04-25 01:40:24 +04:00
2013-05-07 16:00:44 +04:00
# The filter backend classes to use for queryset filtering
filter_backends = api_settings.DEFAULT_FILTER_BACKENDS
2013-04-25 01:40:24 +04:00
# The following attribute may be subject to change,
# and should be considered private API.
paginator_class = Paginator
2013-04-25 20:40:17 +04:00
2012-09-30 20:31:28 +04:00
def get_serializer_context(self):
2012-10-01 18:49:19 +04:00
"""
Extra context provided to the serializer class.
"""
2012-09-30 20:31:28 +04:00
return {
'request': self.request,
2012-10-05 17:22:02 +04:00
'format': self.format_kwarg,
2012-10-01 18:49:19 +04:00
'view': self
2012-09-30 20:31:28 +04:00
}
2014-08-29 19:46:26 +04:00
def get_serializer(self, instance=None, data=None, many=False, partial=False):
2012-11-17 03:22:15 +04:00
"""
Return the serializer instance that should be used for validating and
deserializing input, and for serializing output.
"""
2012-10-01 18:49:19 +04:00
serializer_class = self.get_serializer_class()
2012-09-30 20:31:28 +04:00
context = self.get_serializer_context()
2014-08-29 19:46:26 +04:00
return serializer_class(
instance, data=data, many=many, partial=partial, context=context
)
2013-04-25 01:40:24 +04:00
def get_pagination_serializer(self, page):
2012-10-01 18:49:19 +04:00
"""
Return a serializer instance to use with paginated data.
2012-10-01 18:49:19 +04:00
"""
class SerializerClass(self.pagination_serializer_class):
class Meta:
object_serializer_class = self.get_serializer_class()
pagination_serializer_class = SerializerClass
2012-10-01 18:49:19 +04:00
context = self.get_serializer_context()
return pagination_serializer_class(instance=page, context=context)
def paginate_queryset(self, queryset):
"""
2013-04-25 20:40:17 +04:00
Paginate a queryset if required, either returning a page object,
or `None` if pagination is not configured for this view.
"""
page_size = self.get_paginate_by()
if not page_size:
return None
2013-04-25 20:40:17 +04:00
2014-08-29 13:57:24 +04:00
paginator = self.paginator_class(queryset, page_size)
2013-04-25 01:40:24 +04:00
page_kwarg = self.kwargs.get(self.page_kwarg)
2014-09-26 13:46:52 +04:00
page_query_param = self.request.query_params.get(self.page_kwarg)
2013-04-25 01:40:24 +04:00
page = page_kwarg or page_query_param or 1
try:
page_number = paginator.validate_number(page)
except InvalidPage:
if page == 'last':
page_number = paginator.num_pages
else:
raise Http404(_("Page is not 'last', nor can it be converted to an int."))
try:
page = paginator.page(page_number)
2014-08-19 16:28:07 +04:00
except InvalidPage as exc:
error_format = _('Invalid page (%(page_number)s): %(message)s')
raise Http404(error_format % {
'page_number': page_number,
'message': str(exc)
})
2013-04-25 20:40:17 +04:00
return page
def filter_queryset(self, queryset):
"""
Given a queryset, filter it with whichever filter backend is in use.
2013-04-23 14:59:13 +04:00
You are unlikely to want to override this method, although you may need
to call it either from a list view, or from a custom `get_object`
method if you want to apply the configured filtering backend to the
default queryset.
"""
2013-10-24 17:39:02 +04:00
for backend in self.get_filter_backends():
queryset = backend().filter_queryset(self.request, queryset, self)
return queryset
def get_filter_backends(self):
"""
Returns the list of filter backends that this view requires.
"""
2014-08-29 13:48:40 +04:00
return list(self.filter_backends)
2013-05-07 16:00:44 +04:00
2014-08-19 16:54:52 +04:00
# The following methods provide default implementations
# that you may want to override for more complex cases.
def get_paginate_by(self):
2013-04-25 01:40:24 +04:00
"""
Return the size of pages to use with pagination.
If `PAGINATE_BY_PARAM` is set it will attempt to get the page size
from a named query parameter in the url, eg. ?page_size=100
Otherwise defaults to using `self.paginate_by`.
"""
if self.paginate_by_param:
try:
return strict_positive_int(
2014-09-26 13:46:52 +04:00
self.request.query_params[self.paginate_by_param],
cutoff=self.max_paginate_by
)
2013-04-25 01:40:24 +04:00
except (KeyError, ValueError):
pass
return self.paginate_by
def get_serializer_class(self):
"""
Return the class to use for the serializer.
Defaults to using `self.serializer_class`.
You may want to override this if you need to provide different
serializations depending on the incoming request.
2013-06-12 22:00:33 +04:00
(Eg. admins get full serialization, others get basic serialization)
"""
assert self.serializer_class is not None, (
"'%s' should either include a `serializer_class` attribute, "
"or override the `get_serializer_class()` method."
% self.__class__.__name__
)
return self.serializer_class
def get_queryset(self):
"""
Get the list of items for this view.
This must be an iterable, and may be a queryset.
Defaults to using `self.queryset`.
This method should always be used rather than accessing `self.queryset`
directly, as `self.queryset` gets evaluated only once, and those results
are cached for all subsequent requests.
You may want to override this if you need to provide different
querysets depending on the incoming request.
(Eg. return a list of items that is specific to the user)
"""
assert self.queryset is not None, (
"'%s' should either include a `queryset` attribute, "
"or override the `get_queryset()` method."
% self.__class__.__name__
)
queryset = self.queryset
if isinstance(queryset, QuerySet):
# Ensure queryset is re-evaluated on each request.
queryset = queryset.all()
return queryset
def get_object(self):
"""
Returns the object the view is displaying.
You may want to override this if you need to provide non-standard
queryset lookups. Eg if objects are referenced using multiple
keyword arguments in the url conf.
"""
queryset = self.filter_queryset(self.get_queryset())
2013-04-09 22:01:01 +04:00
# Perform the lookup filtering.
2013-10-21 12:47:07 +04:00
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
2013-04-09 22:01:01 +04:00
2014-08-29 15:48:04 +04:00
assert lookup_url_kwarg in self.kwargs, (
'Expected view %s to be called with a URL keyword argument '
'named "%s". Fix your URL conf, or set the `.lookup_field` '
'attribute on the view correctly.' %
(self.__class__.__name__, lookup_url_kwarg)
)
2013-04-09 22:01:01 +04:00
2014-08-29 15:48:04 +04:00
filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
2013-04-11 18:48:18 +04:00
obj = get_object_or_404(queryset, **filter_kwargs)
2013-04-09 22:01:01 +04:00
# May raise a permission denied
self.check_object_permissions(self.request, obj)
2013-04-09 22:01:01 +04:00
return obj
2014-08-19 16:54:52 +04:00
# Concrete view classes that provide method handlers
# by composing the mixin classes with the base view.
class CreateAPIView(mixins.CreateModelMixin,
2012-10-25 16:50:39 +04:00
GenericAPIView):
"""
Concrete view for creating a model instance.
"""
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
class ListAPIView(mixins.ListModelMixin,
GenericAPIView):
"""
Concrete view for listing a queryset.
"""
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
2012-10-03 12:26:15 +04:00
class RetrieveAPIView(mixins.RetrieveModelMixin,
GenericAPIView):
"""
Concrete view for retrieving a model instance.
"""
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
class DestroyAPIView(mixins.DestroyModelMixin,
GenericAPIView):
"""
Concrete view for deleting a model instance.
"""
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
class UpdateAPIView(mixins.UpdateModelMixin,
GenericAPIView):
"""
Concrete view for updating a model instance.
"""
def put(self, request, *args, **kwargs):
2013-01-02 17:39:24 +04:00
return self.update(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
2013-04-05 01:24:30 +04:00
return self.partial_update(request, *args, **kwargs)
class ListCreateAPIView(mixins.ListModelMixin,
mixins.CreateModelMixin,
GenericAPIView):
"""
Concrete view for listing a queryset or creating a model instance.
"""
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
2012-12-13 19:57:17 +04:00
class RetrieveUpdateAPIView(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
GenericAPIView):
2012-12-13 19:57:17 +04:00
"""
Concrete view for retrieving, updating a model instance.
"""
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
2013-04-05 01:24:30 +04:00
return self.partial_update(request, *args, **kwargs)
2012-12-13 23:41:40 +04:00
class RetrieveDestroyAPIView(mixins.RetrieveModelMixin,
mixins.DestroyModelMixin,
GenericAPIView):
"""
Concrete view for retrieving or deleting a model instance.
"""
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
GenericAPIView):
"""
Concrete view for retrieving, updating or deleting a model instance.
"""
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
2013-01-02 17:39:24 +04:00
return self.update(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
2013-04-05 01:24:30 +04:00
return self.partial_update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)