api.py 12 KB

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