api.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. from __future__ import unicode_literals
  2. from collections import OrderedDict
  3. import pytz
  4. from django.conf import settings
  5. from django.contrib.contenttypes.models import ContentType
  6. from django.core.exceptions import ObjectDoesNotExist
  7. from django.db.models import ManyToManyField
  8. from django.http import Http404
  9. from rest_framework import mixins
  10. from rest_framework.exceptions import APIException
  11. from rest_framework.permissions import BasePermission
  12. from rest_framework.relations import PrimaryKeyRelatedField
  13. from rest_framework.response import Response
  14. from rest_framework.serializers import Field, ModelSerializer, RelatedField, ValidationError
  15. from rest_framework.viewsets import GenericViewSet, ViewSet
  16. WRITE_OPERATIONS = ['create', 'update', 'partial_update', 'delete']
  17. class ServiceUnavailable(APIException):
  18. status_code = 503
  19. default_detail = "Service temporarily unavailable, please try again later."
  20. #
  21. # Authentication
  22. #
  23. class IsAuthenticatedOrLoginNotRequired(BasePermission):
  24. """
  25. Returns True if the user is authenticated or LOGIN_REQUIRED is False.
  26. """
  27. def has_permission(self, request, view):
  28. if not settings.LOGIN_REQUIRED:
  29. return True
  30. return request.user.is_authenticated
  31. #
  32. # Fields
  33. #
  34. class TagField(RelatedField):
  35. """
  36. Represent a writable list of Tags associated with an object (use with many=True).
  37. """
  38. def to_internal_value(self, data):
  39. obj = self.parent.parent.instance
  40. content_type = ContentType.objects.get_for_model(obj)
  41. tag, _ = Tag.objects.get_or_create(content_type=content_type, object_id=obj.pk, name=data)
  42. return tag
  43. def to_representation(self, value):
  44. return value.name
  45. class ChoiceFieldSerializer(Field):
  46. """
  47. Represent a ChoiceField as {'value': <DB value>, 'label': <string>}.
  48. """
  49. def __init__(self, choices, **kwargs):
  50. self._choices = dict()
  51. for k, v in choices:
  52. # Unpack grouped choices
  53. if type(v) in [list, tuple]:
  54. for k2, v2 in v:
  55. self._choices[k2] = v2
  56. else:
  57. self._choices[k] = v
  58. super(ChoiceFieldSerializer, self).__init__(**kwargs)
  59. def to_representation(self, obj):
  60. return {'value': obj, 'label': self._choices[obj]}
  61. def to_internal_value(self, data):
  62. return data
  63. class ContentTypeFieldSerializer(Field):
  64. """
  65. Represent a ContentType as '<app_label>.<model>'
  66. """
  67. def to_representation(self, obj):
  68. return "{}.{}".format(obj.app_label, obj.model)
  69. def to_internal_value(self, data):
  70. app_label, model = data.split('.')
  71. try:
  72. return ContentType.objects.get_by_natural_key(app_label=app_label, model=model)
  73. except ContentType.DoesNotExist:
  74. raise ValidationError("Invalid content type")
  75. class TimeZoneField(Field):
  76. """
  77. Represent a pytz time zone.
  78. """
  79. def to_representation(self, obj):
  80. return obj.zone if obj else None
  81. def to_internal_value(self, data):
  82. if not data:
  83. return ""
  84. try:
  85. return pytz.timezone(str(data))
  86. except pytz.exceptions.UnknownTimeZoneError:
  87. raise ValidationError('Invalid time zone "{}"'.format(data))
  88. class SerializedPKRelatedField(PrimaryKeyRelatedField):
  89. """
  90. Extends PrimaryKeyRelatedField to return a serialized object on read. This is useful for representing related
  91. objects in a ManyToManyField while still allowing a set of primary keys to be written.
  92. """
  93. def __init__(self, serializer, **kwargs):
  94. self.serializer = serializer
  95. self.pk_field = kwargs.pop('pk_field', None)
  96. super(SerializedPKRelatedField, self).__init__(**kwargs)
  97. def to_representation(self, value):
  98. return self.serializer(value, context={'request': self.context['request']}).data
  99. #
  100. # Serializers
  101. #
  102. class ValidatedModelSerializer(ModelSerializer):
  103. """
  104. Extends the built-in ModelSerializer to enforce calling clean() on the associated model during validation.
  105. """
  106. def validate(self, data):
  107. # Remove custom field data (if any) prior to model validation
  108. attrs = data.copy()
  109. attrs.pop('custom_fields', None)
  110. # Run clean() on an instance of the model
  111. if self.instance is None:
  112. model = self.Meta.model
  113. # Ignore ManyToManyFields for new instances (a PK is needed for validation)
  114. for field in model._meta.get_fields():
  115. if isinstance(field, ManyToManyField) and field.name in attrs:
  116. attrs.pop(field.name)
  117. instance = self.Meta.model(**attrs)
  118. else:
  119. instance = self.instance
  120. for k, v in attrs.items():
  121. setattr(instance, k, v)
  122. instance.clean()
  123. return data
  124. class WritableNestedSerializer(ModelSerializer):
  125. """
  126. Returns a nested representation of an object on read, but accepts only a primary key on write.
  127. """
  128. def to_internal_value(self, data):
  129. if data is None:
  130. return None
  131. try:
  132. return self.Meta.model.objects.get(pk=data)
  133. except ObjectDoesNotExist:
  134. raise ValidationError("Invalid ID")
  135. #
  136. # Viewsets
  137. #
  138. class ModelViewSet(mixins.CreateModelMixin,
  139. mixins.RetrieveModelMixin,
  140. mixins.UpdateModelMixin,
  141. mixins.DestroyModelMixin,
  142. mixins.ListModelMixin,
  143. GenericViewSet):
  144. """
  145. Accept either a single object or a list of objects to create.
  146. """
  147. def get_serializer(self, *args, **kwargs):
  148. # If a list of objects has been provided, initialize the serializer with many=True
  149. if isinstance(kwargs.get('data', {}), list):
  150. kwargs['many'] = True
  151. return super(ModelViewSet, self).get_serializer(*args, **kwargs)
  152. class FieldChoicesViewSet(ViewSet):
  153. """
  154. Expose the built-in numeric values which represent static choices for a model's field.
  155. """
  156. permission_classes = [IsAuthenticatedOrLoginNotRequired]
  157. fields = []
  158. def __init__(self, *args, **kwargs):
  159. super(FieldChoicesViewSet, self).__init__(*args, **kwargs)
  160. # Compile a dict of all fields in this view
  161. self._fields = OrderedDict()
  162. for cls, field_list in self.fields:
  163. for field_name in field_list:
  164. model_name = cls._meta.verbose_name.lower().replace(' ', '-')
  165. key = ':'.join([model_name, field_name])
  166. choices = []
  167. for k, v in cls._meta.get_field(field_name).choices:
  168. if type(v) in [list, tuple]:
  169. for k2, v2 in v:
  170. choices.append({
  171. 'value': k2,
  172. 'label': v2,
  173. })
  174. else:
  175. choices.append({
  176. 'value': k,
  177. 'label': v,
  178. })
  179. self._fields[key] = choices
  180. def list(self, request):
  181. return Response(self._fields)
  182. def retrieve(self, request, pk):
  183. if pk not in self._fields:
  184. raise Http404
  185. return Response(self._fields[pk])
  186. def get_view_name(self):
  187. return "Field Choices"