api.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. from collections import OrderedDict
  2. import pytz
  3. from django.conf import settings
  4. from django.contrib.contenttypes.models import ContentType
  5. from django.core.exceptions import FieldError, MultipleObjectsReturned, ObjectDoesNotExist
  6. from django.db.models import ManyToManyField, ProtectedError
  7. from django.http import Http404
  8. from rest_framework.exceptions import APIException
  9. from rest_framework.permissions import BasePermission
  10. from rest_framework.relations import PrimaryKeyRelatedField, RelatedField
  11. from rest_framework.response import Response
  12. from rest_framework.serializers import Field, ModelSerializer, ValidationError
  13. from rest_framework.viewsets import ModelViewSet as _ModelViewSet, ViewSet
  14. from .utils import dict_to_filter_params, dynamic_import
  15. class ServiceUnavailable(APIException):
  16. status_code = 503
  17. default_detail = "Service temporarily unavailable, please try again later."
  18. class SerializerNotFound(Exception):
  19. pass
  20. def get_serializer_for_model(model, prefix=''):
  21. """
  22. Dynamically resolve and return the appropriate serializer for a model.
  23. """
  24. app_name, model_name = model._meta.label.split('.')
  25. serializer_name = '{}.api.serializers.{}{}Serializer'.format(
  26. app_name, prefix, model_name
  27. )
  28. try:
  29. return dynamic_import(serializer_name)
  30. except AttributeError:
  31. raise SerializerNotFound(
  32. "Could not determine serializer for {}.{} with prefix '{}'".format(app_name, model_name, prefix)
  33. )
  34. #
  35. # Authentication
  36. #
  37. class IsAuthenticatedOrLoginNotRequired(BasePermission):
  38. """
  39. Returns True if the user is authenticated or LOGIN_REQUIRED is False.
  40. """
  41. def has_permission(self, request, view):
  42. if not settings.LOGIN_REQUIRED:
  43. return True
  44. return request.user.is_authenticated
  45. #
  46. # Fields
  47. #
  48. class ChoiceField(Field):
  49. """
  50. Represent a ChoiceField as {'value': <DB value>, 'label': <string>}.
  51. """
  52. def __init__(self, choices, **kwargs):
  53. self._choices = dict()
  54. for k, v in choices:
  55. # Unpack grouped choices
  56. if type(v) in [list, tuple]:
  57. for k2, v2 in v:
  58. self._choices[k2] = v2
  59. else:
  60. self._choices[k] = v
  61. super().__init__(**kwargs)
  62. def to_representation(self, obj):
  63. if obj is '':
  64. return None
  65. data = OrderedDict([
  66. ('value', obj),
  67. ('label', self._choices[obj])
  68. ])
  69. return data
  70. def to_internal_value(self, data):
  71. # Provide an explicit error message if the request is trying to write a dict or list
  72. if isinstance(data, (dict, list)):
  73. raise ValidationError('Value must be passed directly (e.g. "foo": 123); do not use a dictionary or list.')
  74. # Check for string representations of boolean/integer values
  75. if hasattr(data, 'lower'):
  76. if data.lower() == 'true':
  77. data = True
  78. elif data.lower() == 'false':
  79. data = False
  80. else:
  81. try:
  82. data = int(data)
  83. except ValueError:
  84. pass
  85. try:
  86. if data in self._choices:
  87. return data
  88. except TypeError: # Input is an unhashable type
  89. pass
  90. raise ValidationError("{} is not a valid choice.".format(data))
  91. @property
  92. def choices(self):
  93. return self._choices
  94. class ContentTypeField(RelatedField):
  95. """
  96. Represent a ContentType as '<app_label>.<model>'
  97. """
  98. default_error_messages = {
  99. "does_not_exist": "Invalid content type: {content_type}",
  100. "invalid": "Invalid value. Specify a content type as '<app_label>.<model_name>'.",
  101. }
  102. def to_internal_value(self, data):
  103. try:
  104. app_label, model = data.split('.')
  105. return ContentType.objects.get_by_natural_key(app_label=app_label, model=model)
  106. except ObjectDoesNotExist:
  107. self.fail('does_not_exist', content_type=data)
  108. except (TypeError, ValueError):
  109. self.fail('invalid')
  110. def to_representation(self, obj):
  111. return "{}.{}".format(obj.app_label, obj.model)
  112. class TimeZoneField(Field):
  113. """
  114. Represent a pytz time zone.
  115. """
  116. def to_representation(self, obj):
  117. return obj.zone if obj else None
  118. def to_internal_value(self, data):
  119. if not data:
  120. return ""
  121. if data not in pytz.common_timezones:
  122. raise ValidationError('Unknown time zone "{}" (see pytz.common_timezones for all options)'.format(data))
  123. return pytz.timezone(data)
  124. class SerializedPKRelatedField(PrimaryKeyRelatedField):
  125. """
  126. Extends PrimaryKeyRelatedField to return a serialized object on read. This is useful for representing related
  127. objects in a ManyToManyField while still allowing a set of primary keys to be written.
  128. """
  129. def __init__(self, serializer, **kwargs):
  130. self.serializer = serializer
  131. self.pk_field = kwargs.pop('pk_field', None)
  132. super().__init__(**kwargs)
  133. def to_representation(self, value):
  134. return self.serializer(value, context={'request': self.context['request']}).data
  135. #
  136. # Serializers
  137. #
  138. # TODO: We should probably take a fresh look at exactly what we're doing with this. There might be a more elegant
  139. # way to enforce model validation on the serializer.
  140. class ValidatedModelSerializer(ModelSerializer):
  141. """
  142. Extends the built-in ModelSerializer to enforce calling clean() on the associated model during validation.
  143. """
  144. def validate(self, data):
  145. # Remove custom fields data and tags (if any) prior to model validation
  146. attrs = data.copy()
  147. attrs.pop('custom_fields', None)
  148. attrs.pop('tags', None)
  149. # Skip ManyToManyFields
  150. for field in self.Meta.model._meta.get_fields():
  151. if isinstance(field, ManyToManyField):
  152. attrs.pop(field.name, None)
  153. # Run clean() on an instance of the model
  154. if self.instance is None:
  155. instance = self.Meta.model(**attrs)
  156. else:
  157. instance = self.instance
  158. for k, v in attrs.items():
  159. setattr(instance, k, v)
  160. instance.clean()
  161. return data
  162. class WritableNestedSerializer(ModelSerializer):
  163. """
  164. Returns a nested representation of an object on read, but accepts only a primary key on write.
  165. """
  166. def to_internal_value(self, data):
  167. if data is None:
  168. return None
  169. # Dictionary of related object attributes
  170. if isinstance(data, dict):
  171. params = dict_to_filter_params(data)
  172. try:
  173. return self.Meta.model.objects.get(**params)
  174. except ObjectDoesNotExist:
  175. raise ValidationError(
  176. "Related object not found using the provided attributes: {}".format(params)
  177. )
  178. except MultipleObjectsReturned:
  179. raise ValidationError(
  180. "Multiple objects match the provided attributes: {}".format(params)
  181. )
  182. except FieldError as e:
  183. raise ValidationError(e)
  184. # Integer PK of related object
  185. if isinstance(data, int):
  186. pk = data
  187. else:
  188. try:
  189. # PK might have been mistakenly passed as a string
  190. pk = int(data)
  191. except (TypeError, ValueError):
  192. raise ValidationError(
  193. "Related objects must be referenced by numeric ID or by dictionary of attributes. Received an "
  194. "unrecognized value: {}".format(data)
  195. )
  196. # Look up object by PK
  197. try:
  198. return self.Meta.model.objects.get(pk=int(data))
  199. except ObjectDoesNotExist:
  200. raise ValidationError(
  201. "Related object not found using the provided numeric ID: {}".format(pk)
  202. )
  203. #
  204. # Viewsets
  205. #
  206. class ModelViewSet(_ModelViewSet):
  207. """
  208. Accept either a single object or a list of objects to create.
  209. """
  210. def get_serializer(self, *args, **kwargs):
  211. # If a list of objects has been provided, initialize the serializer with many=True
  212. if isinstance(kwargs.get('data', {}), list):
  213. kwargs['many'] = True
  214. return super().get_serializer(*args, **kwargs)
  215. def get_serializer_class(self):
  216. # If 'brief' has been passed as a query param, find and return the nested serializer for this model, if one
  217. # exists
  218. request = self.get_serializer_context()['request']
  219. if request.query_params.get('brief', False):
  220. try:
  221. return get_serializer_for_model(self.queryset.model, prefix='Nested')
  222. except SerializerNotFound:
  223. pass
  224. # Fall back to the hard-coded serializer class
  225. return self.serializer_class
  226. def dispatch(self, request, *args, **kwargs):
  227. try:
  228. return super().dispatch(request, *args, **kwargs)
  229. except ProtectedError as e:
  230. models = ['{} ({})'.format(o, o._meta) for o in e.protected_objects.all()]
  231. msg = 'Unable to delete object. The following dependent objects were found: {}'.format(', '.join(models))
  232. return self.finalize_response(
  233. request,
  234. Response({'detail': msg}, status=409),
  235. *args,
  236. **kwargs
  237. )
  238. def list(self, *args, **kwargs):
  239. """
  240. Call to super to allow for caching
  241. """
  242. return super().list(*args, **kwargs)
  243. def retrieve(self, *args, **kwargs):
  244. """
  245. Call to super to allow for caching
  246. """
  247. return super().retrieve(*args, **kwargs)
  248. class FieldChoicesViewSet(ViewSet):
  249. """
  250. Expose the built-in numeric values which represent static choices for a model's field.
  251. """
  252. permission_classes = [IsAuthenticatedOrLoginNotRequired]
  253. fields = []
  254. def __init__(self, *args, **kwargs):
  255. super().__init__(*args, **kwargs)
  256. # Compile a dict of all fields in this view
  257. self._fields = OrderedDict()
  258. for cls, field_list in self.fields:
  259. for field_name in field_list:
  260. model_name = cls._meta.verbose_name.lower().replace(' ', '-')
  261. key = ':'.join([model_name, field_name])
  262. serializer = get_serializer_for_model(cls)()
  263. choices = []
  264. for k, v in serializer.get_fields()[field_name].choices.items():
  265. if type(v) in [list, tuple]:
  266. for k2, v2 in v:
  267. choices.append({
  268. 'value': k2,
  269. 'label': v2,
  270. })
  271. else:
  272. choices.append({
  273. 'value': k,
  274. 'label': v,
  275. })
  276. self._fields[key] = choices
  277. def list(self, request):
  278. return Response(self._fields)
  279. def retrieve(self, request, pk):
  280. if pk not in self._fields:
  281. raise Http404
  282. return Response(self._fields[pk])
  283. def get_view_name(self):
  284. return "Field Choices"