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 | |
Scott Baker | 71b21f6 | 2014-12-17 18:22:33 -0800 | [diff] [blame] | 45 | class XOSModelSerializer(serializers.ModelSerializer): |
| 46 | def save_object(self, obj, **kwargs): |
| 47 | |
| 48 | """ rest_framework can't deal with ManyToMany relations that have a |
| 49 | through table. In plstackapi, most of the through tables we have |
| 50 | use defaults or blank fields, so there's no reason why we shouldn't |
| 51 | be able to save these objects. |
| 52 | |
| 53 | So, let's strip out these m2m relations, and deal with them ourself. |
| 54 | """ |
| 55 | obj._complex_m2m_data={};
|
| 56 | if getattr(obj, '_m2m_data', None):
|
| 57 | for relatedObject in obj._meta.get_all_related_many_to_many_objects():
|
| 58 | if (relatedObject.field.rel.through._meta.auto_created):
|
| 59 | # These are non-trough ManyToMany relations and
|
| 60 | # can be updated just fine
|
| 61 | continue
|
| 62 | fieldName = relatedObject.get_accessor_name()
|
| 63 | if fieldName in obj._m2m_data.keys():
|
| 64 | obj._complex_m2m_data[fieldName] = (relatedObject, obj._m2m_data[fieldName])
|
| 65 | del obj._m2m_data[fieldName]
|
| 66 |
|
| 67 | serializers.ModelSerializer.save_object(self, obj, **kwargs); |
| 68 | |
| 69 | for (accessor, stuff) in obj._complex_m2m_data.items(): |
| 70 | (relatedObject, data) = stuff |
| 71 | through = relatedObject.field.rel.through |
| 72 | local_fieldName = relatedObject.field.m2m_reverse_field_name() |
Scott Baker | d923b81 | 2014-12-18 12:59:04 -0800 | [diff] [blame^] | 73 | remote_fieldName = relatedObject.field.m2m_field_name() |
| 74 | |
| 75 | # get the current set of existing relations |
Scott Baker | 71b21f6 | 2014-12-17 18:22:33 -0800 | [diff] [blame] | 76 | existing = through.objects.filter(**{local_fieldName: obj}); |
Scott Baker | 71b21f6 | 2014-12-17 18:22:33 -0800 | [diff] [blame] | 77 | |
Scott Baker | d923b81 | 2014-12-18 12:59:04 -0800 | [diff] [blame^] | 78 | data_ids = [item.id for item in data] |
| 79 | existing_ids = [getattr(item,remote_fieldName).id for item in existing] |
Scott Baker | 71b21f6 | 2014-12-17 18:22:33 -0800 | [diff] [blame] | 80 | |
Scott Baker | d923b81 | 2014-12-18 12:59:04 -0800 | [diff] [blame^] | 81 | #print "data_ids", data_ids |
| 82 | #print "existing_ids", existing_ids |
| 83 | |
| 84 | # remove relations that are in 'existing' but not in 'data' |
| 85 | for item in list(existing): |
| 86 | if (getattr(item,remote_fieldName).id not in data_ids): |
| 87 | print "delete", getattr(item,remote_fieldName) |
| 88 | item.delete() #(purge=True) |
| 89 | |
| 90 | # add relations that are in 'data' but not in 'existing' |
| 91 | for item in data: |
| 92 | if (item.id not in existing_ids): |
| 93 | #print "add", item |
| 94 | newModel = through(**{local_fieldName: obj, remote_fieldName: item}) |
| 95 | newModel.save() |
Scott Baker | 71b21f6 | 2014-12-17 18:22:33 -0800 | [diff] [blame] | 96 | |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 97 | {% for object in generator.all %} |
| 98 | |
| 99 | class {{ object.camel }}Serializer(serializers.HyperlinkedModelSerializer): |
Sapan Bhatia | f69dd5c | 2014-10-08 11:34:23 -0400 | [diff] [blame] | 100 | id = serializers.Field() |
| 101 | {% for ref in object.refs %} |
| 102 | {% if ref.multi %} |
| 103 | {{ ref.plural }} = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='{{ ref }}-detail') |
| 104 | {% else %} |
| 105 | {{ ref }} = serializers.HyperlinkedRelatedField(read_only=True, view_name='{{ ref }}-detail') |
| 106 | {% endif %} |
| 107 | {% endfor %} |
Scott Baker | b744f1c | 2014-11-21 11:32:24 -0800 | [diff] [blame] | 108 | humanReadableName = serializers.SerializerMethodField("getHumanReadableName") |
Scott Baker | 96eb3fd | 2014-11-25 00:53:25 -0800 | [diff] [blame] | 109 | validators = serializers.SerializerMethodField("getValidators") |
Scott Baker | b744f1c | 2014-11-21 11:32:24 -0800 | [diff] [blame] | 110 | def getHumanReadableName(self, obj):
|
| 111 | return str(obj) |
Scott Baker | 96eb3fd | 2014-11-25 00:53:25 -0800 | [diff] [blame] | 112 | def getValidators(self, obj): |
| 113 | try: |
| 114 | return obj.getValidators() |
| 115 | except: |
| 116 | return None |
Sapan Bhatia | f69dd5c | 2014-10-08 11:34:23 -0400 | [diff] [blame] | 117 | class Meta: |
| 118 | model = {{ object.camel }} |
Scott Baker | 96eb3fd | 2014-11-25 00:53:25 -0800 | [diff] [blame] | 119 | 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] | 120 | |
Scott Baker | 71b21f6 | 2014-12-17 18:22:33 -0800 | [diff] [blame] | 121 | class {{ object.camel }}IdSerializer(XOSModelSerializer): |
Sapan Bhatia | f69dd5c | 2014-10-08 11:34:23 -0400 | [diff] [blame] | 122 | id = serializers.Field() |
| 123 | {% for ref in object.refs %} |
| 124 | {% if ref.multi %} |
Scott Baker | 71b21f6 | 2014-12-17 18:22:33 -0800 | [diff] [blame] | 125 | {{ ref.plural }} = serializers.PrimaryKeyRelatedField(many=True) #, read_only=True) #, view_name='{{ ref }}-detail') |
Sapan Bhatia | f69dd5c | 2014-10-08 11:34:23 -0400 | [diff] [blame] | 126 | {% else %} |
Scott Baker | 71b21f6 | 2014-12-17 18:22:33 -0800 | [diff] [blame] | 127 | {{ ref }} = serializers.PrimaryKeyRelatedField() # read_only=True) #, view_name='{{ ref }}-detail') |
Sapan Bhatia | f69dd5c | 2014-10-08 11:34:23 -0400 | [diff] [blame] | 128 | {% endif %} |
| 129 | {% endfor %} |
Scott Baker | b744f1c | 2014-11-21 11:32:24 -0800 | [diff] [blame] | 130 | humanReadableName = serializers.SerializerMethodField("getHumanReadableName") |
Scott Baker | 96eb3fd | 2014-11-25 00:53:25 -0800 | [diff] [blame] | 131 | validators = serializers.SerializerMethodField("getValidators") |
Scott Baker | b744f1c | 2014-11-21 11:32:24 -0800 | [diff] [blame] | 132 | def getHumanReadableName(self, obj):
|
| 133 | return str(obj)
|
Scott Baker | 96eb3fd | 2014-11-25 00:53:25 -0800 | [diff] [blame] | 134 | def getValidators(self, obj):
|
| 135 | try: |
| 136 | return obj.getValidators() |
| 137 | except: |
| 138 | return None
|
Scott Baker | 71b21f6 | 2014-12-17 18:22:33 -0800 | [diff] [blame] | 139 | class Meta:
|
Sapan Bhatia | f69dd5c | 2014-10-08 11:34:23 -0400 | [diff] [blame] | 140 | model = {{ object.camel }} |
Scott Baker | 96eb3fd | 2014-11-25 00:53:25 -0800 | [diff] [blame] | 141 | 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] | 142 | |
| 143 | |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 144 | {% endfor %} |
| 145 | |
| 146 | serializerLookUp = { |
| 147 | {% for object in generator.all %} |
| 148 | {{ object.camel }}: {{ object.camel }}Serializer, |
| 149 | {% endfor %} |
| 150 | None: None, |
| 151 | } |
| 152 | |
Scott Baker | 89a7b7c | 2014-10-07 00:10:17 -0700 | [diff] [blame] | 153 | class PlanetStackRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView): |
| 154 | |
| 155 | # To handle fine-grained field permissions, we have to check can_update |
| 156 | # the object has been updated but before it has been saved. |
| 157 | |
| 158 | def update(self, request, *args, **kwargs):
|
| 159 | partial = kwargs.pop('partial', False)
|
| 160 | self.object = self.get_object_or_none()
|
| 161 |
|
| 162 | serializer = self.get_serializer(self.object, data=request.DATA,
|
| 163 | files=request.FILES, partial=partial)
|
| 164 |
|
| 165 | if not serializer.is_valid():
|
Scott Baker | 96eb3fd | 2014-11-25 00:53:25 -0800 | [diff] [blame] | 166 | response = {"error": "validation",
|
| 167 | "specific_error": "not serializer.is_valid()",
|
| 168 | "reasons": serializer.errors}
|
| 169 | return Response(response, status=status.HTTP_400_BAD_REQUEST)
|
Scott Baker | 89a7b7c | 2014-10-07 00:10:17 -0700 | [diff] [blame] | 170 |
|
| 171 | try:
|
| 172 | self.pre_save(serializer.object)
|
| 173 | except ValidationError as err:
|
| 174 | # full_clean on model instance may be called in pre_save,
|
| 175 | # so we have to handle eventual errors.
|
Scott Baker | 96eb3fd | 2014-11-25 00:53:25 -0800 | [diff] [blame] | 176 | response = {"error": "validation",
|
| 177 | "specific_error": "ValidationError in pre_save",
|
| 178 | "reasons": err.message_dict}
|
| 179 | return Response(response, status=status.HTTP_400_BAD_REQUEST)
|
Scott Baker | 89a7b7c | 2014-10-07 00:10:17 -0700 | [diff] [blame] | 180 |
|
| 181 | if serializer.object is not None:
|
| 182 | if not serializer.object.can_update(request.user):
|
| 183 | return Response(status=status.HTTP_400_BAD_REQUEST)
|
| 184 |
|
| 185 | if self.object is None:
|
| 186 | self.object = serializer.save(force_insert=True)
|
| 187 | self.post_save(self.object, created=True)
|
| 188 | return Response(serializer.data, status=status.HTTP_201_CREATED)
|
| 189 |
|
| 190 | self.object = serializer.save(force_update=True)
|
| 191 | self.post_save(self.object, created=False)
|
| 192 | return Response(serializer.data, status=status.HTTP_200_OK) |
| 193 | |
| 194 | def destroy(self, request, *args, **kwargs): |
| 195 | obj = self.get_object() |
| 196 | if obj.can_update(request.user): |
Scott Baker | adcbf7a | 2014-10-09 11:09:15 -0700 | [diff] [blame] | 197 | return super(generics.RetrieveUpdateDestroyAPIView, self).destroy(request, *args, **kwargs) |
Scott Baker | 89a7b7c | 2014-10-07 00:10:17 -0700 | [diff] [blame] | 198 | else: |
| 199 | return Response(status=status.HTTP_400_BAD_REQUEST) |
| 200 | |
| 201 | |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 202 | # Based on core/views/*.py |
| 203 | {% for object in generator.all %} |
| 204 | |
| 205 | class {{ object.camel }}List(generics.ListCreateAPIView): |
Sapan Bhatia | df2b49e | 2014-01-28 19:41:07 -0500 | [diff] [blame] | 206 | queryset = {{ object.camel }}.objects.select_related().all() |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 207 | serializer_class = {{ object.camel }}Serializer |
Scott Baker | 9a27092 | 2014-07-03 18:01:30 -0700 | [diff] [blame] | 208 | id_serializer_class = {{ object.camel }}IdSerializer |
Scott Baker | 46b5854 | 2014-08-11 17:26:12 -0700 | [diff] [blame] | 209 | filter_backends = (filters.DjangoFilterBackend,) |
| 210 | 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] | 211 | |
| 212 | def get_serializer_class(self): |
| 213 | no_hyperlinks = self.request.QUERY_PARAMS.get('no_hyperlinks', False) |
| 214 | if (no_hyperlinks): |
| 215 | return self.id_serializer_class |
| 216 | else: |
| 217 | return self.serializer_class |
| 218 | |
Tony Mack | eb8eb31 | 2014-02-04 20:50:39 -0500 | [diff] [blame] | 219 | def get_queryset(self): |
Tony Mack | 8f04ee3 | 2014-02-05 10:27:39 -0500 | [diff] [blame] | 220 | return {{ object.camel }}.select_by_user(self.request.user) |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 221 | |
Tony Mack | 9525eba | 2014-02-05 10:57:21 -0500 | [diff] [blame] | 222 | def create(self, request, *args, **kwargs): |
Scott Baker | 6ad1790 | 2014-11-12 01:12:28 -0800 | [diff] [blame] | 223 | serializer = self.get_serializer(data=request.DATA, files=request.FILES) |
| 224 | if not (serializer.is_valid()): |
Scott Baker | 96eb3fd | 2014-11-25 00:53:25 -0800 | [diff] [blame] | 225 | response = {"error": "validation", |
| 226 | "specific_error": "not serializer.is_valid()",
|
| 227 | "reasons": serializer.errors}
|
| 228 | return Response(response, status=status.HTTP_400_BAD_REQUEST) |
Scott Baker | 6ad1790 | 2014-11-12 01:12:28 -0800 | [diff] [blame] | 229 | obj = serializer.object |
Scott Baker | adcbf7a | 2014-10-09 11:09:15 -0700 | [diff] [blame] | 230 | obj.caller = request.user |
| 231 | if obj.can_update(request.user): |
| 232 | return super({{ object.camel }}List, self).create(request, *args, **kwargs) |
| 233 | else: |
| 234 | raise Exception("failed obj.can_update") |
| 235 | |
Sapan Bhatia | f69dd5c | 2014-10-08 11:34:23 -0400 | [diff] [blame] | 236 | ret = super({{ object.camel }}List, self).create(request, *args, **kwargs) |
| 237 | if (ret.status_code%100 != 200): |
| 238 | raise Exception(ret.data) |
Scott Baker | adcbf7a | 2014-10-09 11:09:15 -0700 | [diff] [blame] | 239 | |
| 240 | return ret |
| 241 | |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 242 | |
Scott Baker | 89a7b7c | 2014-10-07 00:10:17 -0700 | [diff] [blame] | 243 | class {{ object.camel }}Detail(PlanetStackRetrieveUpdateDestroyAPIView): |
Sapan Bhatia | df2b49e | 2014-01-28 19:41:07 -0500 | [diff] [blame] | 244 | queryset = {{ object.camel }}.objects.select_related().all() |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 245 | serializer_class = {{ object.camel }}Serializer |
Scott Baker | 46b5854 | 2014-08-11 17:26:12 -0700 | [diff] [blame] | 246 | id_serializer_class = {{ object.camel }}IdSerializer |
| 247 | |
| 248 | def get_serializer_class(self): |
| 249 | no_hyperlinks = self.request.QUERY_PARAMS.get('no_hyperlinks', False) |
| 250 | if (no_hyperlinks): |
| 251 | return self.id_serializer_class |
| 252 | else: |
| 253 | return self.serializer_class |
Tony Mack | eb8eb31 | 2014-02-04 20:50:39 -0500 | [diff] [blame] | 254 | |
| 255 | def get_queryset(self): |
Tony Mack | 9525eba | 2014-02-05 10:57:21 -0500 | [diff] [blame] | 256 | return {{ object.camel }}.select_by_user(self.request.user) |
| 257 | |
Scott Baker | 89a7b7c | 2014-10-07 00:10:17 -0700 | [diff] [blame] | 258 | # update() is handled by PlanetStackRetrieveUpdateDestroyAPIView |
Tony Mack | 9525eba | 2014-02-05 10:57:21 -0500 | [diff] [blame] | 259 | |
Scott Baker | 89a7b7c | 2014-10-07 00:10:17 -0700 | [diff] [blame] | 260 | # destroy() is handled by PlanetStackRetrieveUpdateDestroyAPIView |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 261 | |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 262 | {% endfor %} |