blob: e3f1b64cb4902a26ecccd4e4d0ac58ada91fa5de [file] [log] [blame]
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -05001from rest_framework.decorators import api_view
2from rest_framework.response import Response
3from rest_framework.reverse import reverse
4from rest_framework import serializers
Sapan Bhatiadf2b49e2014-01-28 19:41:07 -05005from rest_framework import generics
Scott Baker89a7b7c2014-10-07 00:10:17 -07006from rest_framework import status
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -05007from core.models import *
8from django.forms import widgets
Scott Baker46b58542014-08-11 17:26:12 -07009from rest_framework import filters
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -050010
11"""
Sapan Bhatiaf69dd5c2014-10-08 11:34:23 -040012 Schema of the generator object:
13 all: Set of all Model objects
14 all_if(regex): Set of Model objects that match regex
15
16 Model object:
17 plural: English plural of object name
18 camel: CamelCase version of object name
19 refs: list of references to other Model objects
20 props: list of properties minus refs
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -050021
Sapan Bhatiaf69dd5c2014-10-08 11:34:23 -040022 TODO: Deal with subnets
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -050023"""
24
25# Based on api_root.py
26
27@api_view(['GET'])
28def api_root(request, format=None):
29 return Response({
Sapan Bhatiaf69dd5c2014-10-08 11:34:23 -040030 {% for object in generator.all %}'{{ object.plural }}': reverse('{{ object }}-list', request=request, format=format),
31 {% endfor %}
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -050032 })
33
34# Based on serializers.py
35
36{% for object in generator.all %}
37
38class {{ object.camel }}Serializer(serializers.HyperlinkedModelSerializer):
Sapan Bhatiaf69dd5c2014-10-08 11:34:23 -040039 id = serializers.Field()
40 {% for ref in object.refs %}
41 {% if ref.multi %}
42 {{ ref.plural }} = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='{{ ref }}-detail')
43 {% else %}
44 {{ ref }} = serializers.HyperlinkedRelatedField(read_only=True, view_name='{{ ref }}-detail')
45 {% endif %}
46 {% endfor %}
47 class Meta:
48 model = {{ object.camel }}
49 fields = ({% for prop in object.props %}'{{ prop }}',{% endfor %}{% for ref in object.refs %}{%if ref.multi %}'{{ ref.plural }}'{% else %}'{{ ref }}'{% endif %},{% endfor %})
Scott Baker9a270922014-07-03 18:01:30 -070050
51class {{ object.camel }}IdSerializer(serializers.ModelSerializer):
Sapan Bhatiaf69dd5c2014-10-08 11:34:23 -040052 id = serializers.Field()
53 {% for ref in object.refs %}
54 {% if ref.multi %}
55 {{ ref.plural }} = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='{{ ref }}-detail')
56 {% else %}
57 {{ ref }} = serializers.HyperlinkedRelatedField(read_only=True, view_name='{{ ref }}-detail')
58 {% endif %}
59 {% endfor %}
60 class Meta:
61 model = {{ object.camel }}
62 fields = ({% for prop in object.props %}'{{ prop }}',{% endfor %}{% for ref in object.refs %}{%if ref.multi %}'{{ ref.plural }}'{% else %}'{{ ref }}'{% endif %},{% endfor %})
Scott Baker9a270922014-07-03 18:01:30 -070063
64
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -050065{% endfor %}
66
67serializerLookUp = {
68{% for object in generator.all %}
69 {{ object.camel }}: {{ object.camel }}Serializer,
70{% endfor %}
71 None: None,
72 }
73
Scott Baker89a7b7c2014-10-07 00:10:17 -070074class PlanetStackRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
75
76 # To handle fine-grained field permissions, we have to check can_update
77 # the object has been updated but before it has been saved.
78
79 def update(self, request, *args, **kwargs):
80 partial = kwargs.pop('partial', False)
81 self.object = self.get_object_or_none()
82
83 serializer = self.get_serializer(self.object, data=request.DATA,
84 files=request.FILES, partial=partial)
85
86 if not serializer.is_valid():
87 print "UpdateModelMixin: not serializer.is_valid"
88 print serializer.errors
89 return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
90
91 try:
92 self.pre_save(serializer.object)
93 except ValidationError as err:
94 # full_clean on model instance may be called in pre_save,
95 # so we have to handle eventual errors.
96 return Response(err.message_dict, status=status.HTTP_400_BAD_REQUEST)
97
98 if serializer.object is not None:
99 if not serializer.object.can_update(request.user):
100 return Response(status=status.HTTP_400_BAD_REQUEST)
101
102 if self.object is None:
103 self.object = serializer.save(force_insert=True)
104 self.post_save(self.object, created=True)
105 return Response(serializer.data, status=status.HTTP_201_CREATED)
106
107 self.object = serializer.save(force_update=True)
108 self.post_save(self.object, created=False)
109 return Response(serializer.data, status=status.HTTP_200_OK)
110
111 def destroy(self, request, *args, **kwargs):
112 obj = self.get_object()
113 if obj.can_update(request.user):
Scott Bakeradcbf7a2014-10-09 11:09:15 -0700114 return super(generics.RetrieveUpdateDestroyAPIView, self).destroy(request, *args, **kwargs)
Scott Baker89a7b7c2014-10-07 00:10:17 -0700115 else:
116 return Response(status=status.HTTP_400_BAD_REQUEST)
117
118
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500119# Based on core/views/*.py
120{% for object in generator.all %}
121
122class {{ object.camel }}List(generics.ListCreateAPIView):
Sapan Bhatiadf2b49e2014-01-28 19:41:07 -0500123 queryset = {{ object.camel }}.objects.select_related().all()
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500124 serializer_class = {{ object.camel }}Serializer
Scott Baker9a270922014-07-03 18:01:30 -0700125 id_serializer_class = {{ object.camel }}IdSerializer
Scott Baker46b58542014-08-11 17:26:12 -0700126 filter_backends = (filters.DjangoFilterBackend,)
127 filter_fields = ({% for prop in object.props %}'{{ prop }}',{% endfor %}{% for ref in object.refs %}{%if ref.multi %}'{{ ref.plural }}'{% else %}'{{ ref }}'{% endif %},{% endfor %})
Scott Baker9a270922014-07-03 18:01:30 -0700128
129 def get_serializer_class(self):
130 no_hyperlinks = self.request.QUERY_PARAMS.get('no_hyperlinks', False)
131 if (no_hyperlinks):
132 return self.id_serializer_class
133 else:
134 return self.serializer_class
135
Tony Mackeb8eb312014-02-04 20:50:39 -0500136 def get_queryset(self):
Tony Mack8f04ee32014-02-05 10:27:39 -0500137 return {{ object.camel }}.select_by_user(self.request.user)
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500138
Tony Mack9525eba2014-02-05 10:57:21 -0500139 def create(self, request, *args, **kwargs):
Scott Bakeradcbf7a2014-10-09 11:09:15 -0700140 obj = {{ object.camel }}(**request.DATA)
141 obj.caller = request.user
142 if obj.can_update(request.user):
143 return super({{ object.camel }}List, self).create(request, *args, **kwargs)
144 else:
145 raise Exception("failed obj.can_update")
146
Sapan Bhatiaf69dd5c2014-10-08 11:34:23 -0400147 ret = super({{ object.camel }}List, self).create(request, *args, **kwargs)
148 if (ret.status_code%100 != 200):
149 raise Exception(ret.data)
Scott Bakeradcbf7a2014-10-09 11:09:15 -0700150
151 return ret
152
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500153
Scott Baker89a7b7c2014-10-07 00:10:17 -0700154class {{ object.camel }}Detail(PlanetStackRetrieveUpdateDestroyAPIView):
Sapan Bhatiadf2b49e2014-01-28 19:41:07 -0500155 queryset = {{ object.camel }}.objects.select_related().all()
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500156 serializer_class = {{ object.camel }}Serializer
Scott Baker46b58542014-08-11 17:26:12 -0700157 id_serializer_class = {{ object.camel }}IdSerializer
158
159 def get_serializer_class(self):
160 no_hyperlinks = self.request.QUERY_PARAMS.get('no_hyperlinks', False)
161 if (no_hyperlinks):
162 return self.id_serializer_class
163 else:
164 return self.serializer_class
Tony Mackeb8eb312014-02-04 20:50:39 -0500165
166 def get_queryset(self):
Tony Mack9525eba2014-02-05 10:57:21 -0500167 return {{ object.camel }}.select_by_user(self.request.user)
168
Scott Baker89a7b7c2014-10-07 00:10:17 -0700169 # update() is handled by PlanetStackRetrieveUpdateDestroyAPIView
Tony Mack9525eba2014-02-05 10:57:21 -0500170
Scott Baker89a7b7c2014-10-07 00:10:17 -0700171 # destroy() is handled by PlanetStackRetrieveUpdateDestroyAPIView
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500172
173{% endfor %}