Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 1 | from rest_framework.decorators import api_view |
| 2 | from rest_framework.response import Response |
| 3 | from rest_framework.reverse import reverse |
| 4 | from rest_framework import serializers |
Sapan Bhatia | df2b49e | 2014-01-28 19:41:07 -0500 | [diff] [blame] | 5 | from rest_framework import generics |
Scott Baker | 89a7b7c | 2014-10-07 00:10:17 -0700 | [diff] [blame] | 6 | from rest_framework import status |
Scott Baker | 6ad1790 | 2014-11-12 01:12:28 -0800 | [diff] [blame] | 7 | from rest_framework.generics import GenericAPIView |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 8 | from core.models import * |
| 9 | from django.forms import widgets |
Scott Baker | 46b5854 | 2014-08-11 17:26:12 -0700 | [diff] [blame] | 10 | from rest_framework import filters |
Scott Baker | f556b92 | 2014-11-10 15:58:58 -0800 | [diff] [blame] | 11 | from django.conf.urls import patterns, url |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 12 | |
| 13 | """ |
Sapan Bhatia | f69dd5c | 2014-10-08 11:34:23 -0400 | [diff] [blame] | 14 | Schema of the generator object: |
| 15 | all: Set of all Model objects |
| 16 | all_if(regex): Set of Model objects that match regex |
Scott Baker | 6ad1790 | 2014-11-12 01:12:28 -0800 | [diff] [blame] | 17 | |
Sapan Bhatia | f69dd5c | 2014-10-08 11:34:23 -0400 | [diff] [blame] | 18 | Model object: |
| 19 | plural: English plural of object name |
| 20 | camel: CamelCase version of object name |
| 21 | refs: list of references to other Model objects |
| 22 | props: list of properties minus refs |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 23 | |
Sapan Bhatia | f69dd5c | 2014-10-08 11:34:23 -0400 | [diff] [blame] | 24 | TODO: Deal with subnets |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 25 | """ |
| 26 | |
Scott Baker | f556b92 | 2014-11-10 15:58:58 -0800 | [diff] [blame] | 27 | def get_REST_patterns(): |
| 28 | return patterns('', |
| 29 | url(r'^plstackapi/$', api_root), |
| 30 | {% for object in generator.all %} |
| 31 | url(r'plstackapi/{{ object.rest_name }}/$', {{ object.camel }}List.as_view(), name='{{ object.singular }}-list'), |
| 32 | url(r'plstackapi/{{ object.rest_name }}/(?P<pk>[a-zA-Z0-9\-]+)/$', {{ object.camel }}Detail.as_view(), name ='{{ object.singular }}-detail'), |
| 33 | {% endfor %} |
| 34 | ) |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 35 | |
| 36 | @api_view(['GET']) |
| 37 | def api_root(request, format=None): |
| 38 | return Response({ |
Sapan Bhatia | f69dd5c | 2014-10-08 11:34:23 -0400 | [diff] [blame] | 39 | {% for object in generator.all %}'{{ object.plural }}': reverse('{{ object }}-list', request=request, format=format), |
| 40 | {% endfor %} |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 41 | }) |
| 42 | |
| 43 | # Based on serializers.py |
| 44 | |
| 45 | {% for object in generator.all %} |
| 46 | |
| 47 | class {{ object.camel }}Serializer(serializers.HyperlinkedModelSerializer): |
Sapan Bhatia | f69dd5c | 2014-10-08 11:34:23 -0400 | [diff] [blame] | 48 | id = serializers.Field() |
| 49 | {% for ref in object.refs %} |
| 50 | {% if ref.multi %} |
| 51 | {{ ref.plural }} = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='{{ ref }}-detail') |
| 52 | {% else %} |
| 53 | {{ ref }} = serializers.HyperlinkedRelatedField(read_only=True, view_name='{{ ref }}-detail') |
| 54 | {% endif %} |
| 55 | {% endfor %} |
Scott Baker | b744f1c | 2014-11-21 11:32:24 -0800 | [diff] [blame] | 56 | humanReadableName = serializers.SerializerMethodField("getHumanReadableName") |
Scott Baker | 96eb3fd | 2014-11-25 00:53:25 -0800 | [diff] [blame] | 57 | validators = serializers.SerializerMethodField("getValidators") |
Scott Baker | b744f1c | 2014-11-21 11:32:24 -0800 | [diff] [blame] | 58 | def getHumanReadableName(self, obj):
|
| 59 | return str(obj) |
Scott Baker | 96eb3fd | 2014-11-25 00:53:25 -0800 | [diff] [blame] | 60 | def getValidators(self, obj): |
| 61 | try: |
| 62 | return obj.getValidators() |
| 63 | except: |
| 64 | return None |
Sapan Bhatia | f69dd5c | 2014-10-08 11:34:23 -0400 | [diff] [blame] | 65 | class Meta: |
| 66 | model = {{ object.camel }} |
Scott Baker | 96eb3fd | 2014-11-25 00:53:25 -0800 | [diff] [blame] | 67 | fields = ('humanReadableName', 'validators', {% for prop in object.props %}'{{ prop }}',{% endfor %}{% for ref in object.refs %}{%if ref.multi %}'{{ ref.plural }}'{% else %}'{{ ref }}'{% endif %},{% endfor %}) |
Scott Baker | 9a27092 | 2014-07-03 18:01:30 -0700 | [diff] [blame] | 68 | |
| 69 | class {{ object.camel }}IdSerializer(serializers.ModelSerializer): |
Sapan Bhatia | f69dd5c | 2014-10-08 11:34:23 -0400 | [diff] [blame] | 70 | id = serializers.Field() |
| 71 | {% for ref in object.refs %} |
| 72 | {% if ref.multi %} |
| 73 | {{ ref.plural }} = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='{{ ref }}-detail') |
| 74 | {% else %} |
| 75 | {{ ref }} = serializers.HyperlinkedRelatedField(read_only=True, view_name='{{ ref }}-detail') |
| 76 | {% endif %} |
| 77 | {% endfor %} |
Scott Baker | b744f1c | 2014-11-21 11:32:24 -0800 | [diff] [blame] | 78 | humanReadableName = serializers.SerializerMethodField("getHumanReadableName") |
Scott Baker | 96eb3fd | 2014-11-25 00:53:25 -0800 | [diff] [blame] | 79 | validators = serializers.SerializerMethodField("getValidators") |
Scott Baker | b744f1c | 2014-11-21 11:32:24 -0800 | [diff] [blame] | 80 | def getHumanReadableName(self, obj):
|
| 81 | return str(obj)
|
Scott Baker | 96eb3fd | 2014-11-25 00:53:25 -0800 | [diff] [blame] | 82 | def getValidators(self, obj):
|
| 83 | try: |
| 84 | return obj.getValidators() |
| 85 | except: |
| 86 | return None
|
Sapan Bhatia | f69dd5c | 2014-10-08 11:34:23 -0400 | [diff] [blame] | 87 | class Meta: |
| 88 | model = {{ object.camel }} |
Scott Baker | 96eb3fd | 2014-11-25 00:53:25 -0800 | [diff] [blame] | 89 | fields = ('humanReadableName', 'validators', {% for prop in object.props %}'{{ prop }}',{% endfor %}{% for ref in object.refs %}{%if ref.multi %}'{{ ref.plural }}'{% else %}'{{ ref }}'{% endif %},{% endfor %}) |
Scott Baker | 9a27092 | 2014-07-03 18:01:30 -0700 | [diff] [blame] | 90 | |
| 91 | |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 92 | {% endfor %} |
| 93 | |
| 94 | serializerLookUp = { |
| 95 | {% for object in generator.all %} |
| 96 | {{ object.camel }}: {{ object.camel }}Serializer, |
| 97 | {% endfor %} |
| 98 | None: None, |
| 99 | } |
| 100 | |
Scott Baker | 89a7b7c | 2014-10-07 00:10:17 -0700 | [diff] [blame] | 101 | class PlanetStackRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView): |
| 102 | |
| 103 | # To handle fine-grained field permissions, we have to check can_update |
| 104 | # the object has been updated but before it has been saved. |
| 105 | |
| 106 | def update(self, request, *args, **kwargs):
|
| 107 | partial = kwargs.pop('partial', False)
|
| 108 | self.object = self.get_object_or_none()
|
| 109 |
|
| 110 | serializer = self.get_serializer(self.object, data=request.DATA,
|
| 111 | files=request.FILES, partial=partial)
|
| 112 |
|
| 113 | if not serializer.is_valid():
|
Scott Baker | 96eb3fd | 2014-11-25 00:53:25 -0800 | [diff] [blame] | 114 | response = {"error": "validation",
|
| 115 | "specific_error": "not serializer.is_valid()",
|
| 116 | "reasons": serializer.errors}
|
| 117 | return Response(response, status=status.HTTP_400_BAD_REQUEST)
|
Scott Baker | 89a7b7c | 2014-10-07 00:10:17 -0700 | [diff] [blame] | 118 |
|
| 119 | try:
|
| 120 | self.pre_save(serializer.object)
|
| 121 | except ValidationError as err:
|
| 122 | # full_clean on model instance may be called in pre_save,
|
| 123 | # so we have to handle eventual errors.
|
Scott Baker | 96eb3fd | 2014-11-25 00:53:25 -0800 | [diff] [blame] | 124 | response = {"error": "validation",
|
| 125 | "specific_error": "ValidationError in pre_save",
|
| 126 | "reasons": err.message_dict}
|
| 127 | return Response(response, status=status.HTTP_400_BAD_REQUEST)
|
Scott Baker | 89a7b7c | 2014-10-07 00:10:17 -0700 | [diff] [blame] | 128 |
|
| 129 | if serializer.object is not None:
|
| 130 | if not serializer.object.can_update(request.user):
|
| 131 | return Response(status=status.HTTP_400_BAD_REQUEST)
|
| 132 |
|
| 133 | if self.object is None:
|
| 134 | self.object = serializer.save(force_insert=True)
|
| 135 | self.post_save(self.object, created=True)
|
| 136 | return Response(serializer.data, status=status.HTTP_201_CREATED)
|
| 137 |
|
| 138 | self.object = serializer.save(force_update=True)
|
| 139 | self.post_save(self.object, created=False)
|
| 140 | return Response(serializer.data, status=status.HTTP_200_OK) |
| 141 | |
| 142 | def destroy(self, request, *args, **kwargs): |
| 143 | obj = self.get_object() |
| 144 | if obj.can_update(request.user): |
Scott Baker | adcbf7a | 2014-10-09 11:09:15 -0700 | [diff] [blame] | 145 | return super(generics.RetrieveUpdateDestroyAPIView, self).destroy(request, *args, **kwargs) |
Scott Baker | 89a7b7c | 2014-10-07 00:10:17 -0700 | [diff] [blame] | 146 | else: |
| 147 | return Response(status=status.HTTP_400_BAD_REQUEST) |
| 148 | |
| 149 | |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 150 | # Based on core/views/*.py |
| 151 | {% for object in generator.all %} |
| 152 | |
| 153 | class {{ object.camel }}List(generics.ListCreateAPIView): |
Sapan Bhatia | df2b49e | 2014-01-28 19:41:07 -0500 | [diff] [blame] | 154 | queryset = {{ object.camel }}.objects.select_related().all() |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 155 | serializer_class = {{ object.camel }}Serializer |
Scott Baker | 9a27092 | 2014-07-03 18:01:30 -0700 | [diff] [blame] | 156 | id_serializer_class = {{ object.camel }}IdSerializer |
Scott Baker | 46b5854 | 2014-08-11 17:26:12 -0700 | [diff] [blame] | 157 | filter_backends = (filters.DjangoFilterBackend,) |
| 158 | filter_fields = ({% for prop in object.props %}'{{ prop }}',{% endfor %}{% for ref in object.refs %}{%if ref.multi %}'{{ ref.plural }}'{% else %}'{{ ref }}'{% endif %},{% endfor %}) |
Scott Baker | 9a27092 | 2014-07-03 18:01:30 -0700 | [diff] [blame] | 159 | |
| 160 | def get_serializer_class(self): |
| 161 | no_hyperlinks = self.request.QUERY_PARAMS.get('no_hyperlinks', False) |
| 162 | if (no_hyperlinks): |
| 163 | return self.id_serializer_class |
| 164 | else: |
| 165 | return self.serializer_class |
| 166 | |
Tony Mack | eb8eb31 | 2014-02-04 20:50:39 -0500 | [diff] [blame] | 167 | def get_queryset(self): |
Tony Mack | 8f04ee3 | 2014-02-05 10:27:39 -0500 | [diff] [blame] | 168 | return {{ object.camel }}.select_by_user(self.request.user) |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 169 | |
Tony Mack | 9525eba | 2014-02-05 10:57:21 -0500 | [diff] [blame] | 170 | def create(self, request, *args, **kwargs): |
Scott Baker | 6ad1790 | 2014-11-12 01:12:28 -0800 | [diff] [blame] | 171 | serializer = self.get_serializer(data=request.DATA, files=request.FILES) |
| 172 | if not (serializer.is_valid()): |
Scott Baker | 96eb3fd | 2014-11-25 00:53:25 -0800 | [diff] [blame] | 173 | response = {"error": "validation", |
| 174 | "specific_error": "not serializer.is_valid()",
|
| 175 | "reasons": serializer.errors}
|
| 176 | return Response(response, status=status.HTTP_400_BAD_REQUEST) |
Scott Baker | 6ad1790 | 2014-11-12 01:12:28 -0800 | [diff] [blame] | 177 | obj = serializer.object |
Scott Baker | adcbf7a | 2014-10-09 11:09:15 -0700 | [diff] [blame] | 178 | obj.caller = request.user |
| 179 | if obj.can_update(request.user): |
| 180 | return super({{ object.camel }}List, self).create(request, *args, **kwargs) |
| 181 | else: |
| 182 | raise Exception("failed obj.can_update") |
| 183 | |
Sapan Bhatia | f69dd5c | 2014-10-08 11:34:23 -0400 | [diff] [blame] | 184 | ret = super({{ object.camel }}List, self).create(request, *args, **kwargs) |
| 185 | if (ret.status_code%100 != 200): |
| 186 | raise Exception(ret.data) |
Scott Baker | adcbf7a | 2014-10-09 11:09:15 -0700 | [diff] [blame] | 187 | |
| 188 | return ret |
| 189 | |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 190 | |
Scott Baker | 89a7b7c | 2014-10-07 00:10:17 -0700 | [diff] [blame] | 191 | class {{ object.camel }}Detail(PlanetStackRetrieveUpdateDestroyAPIView): |
Sapan Bhatia | df2b49e | 2014-01-28 19:41:07 -0500 | [diff] [blame] | 192 | queryset = {{ object.camel }}.objects.select_related().all() |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 193 | serializer_class = {{ object.camel }}Serializer |
Scott Baker | 46b5854 | 2014-08-11 17:26:12 -0700 | [diff] [blame] | 194 | id_serializer_class = {{ object.camel }}IdSerializer |
| 195 | |
| 196 | def get_serializer_class(self): |
| 197 | no_hyperlinks = self.request.QUERY_PARAMS.get('no_hyperlinks', False) |
| 198 | if (no_hyperlinks): |
| 199 | return self.id_serializer_class |
| 200 | else: |
| 201 | return self.serializer_class |
Tony Mack | eb8eb31 | 2014-02-04 20:50:39 -0500 | [diff] [blame] | 202 | |
| 203 | def get_queryset(self): |
Tony Mack | 9525eba | 2014-02-05 10:57:21 -0500 | [diff] [blame] | 204 | return {{ object.camel }}.select_by_user(self.request.user) |
| 205 | |
Scott Baker | 89a7b7c | 2014-10-07 00:10:17 -0700 | [diff] [blame] | 206 | # update() is handled by PlanetStackRetrieveUpdateDestroyAPIView |
Tony Mack | 9525eba | 2014-02-05 10:57:21 -0500 | [diff] [blame] | 207 | |
Scott Baker | 89a7b7c | 2014-10-07 00:10:17 -0700 | [diff] [blame] | 208 | # destroy() is handled by PlanetStackRetrieveUpdateDestroyAPIView |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 209 | |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 210 | {% endfor %} |