blob: 710f05135c91b64ce413a0126ded3d817a216e93 [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 Bakerdcb9b5d2014-10-07 00:10:17 -07006from rest_framework import status
Scott Bakerc480fb22014-11-12 01:12:28 -08007from rest_framework.generics import GenericAPIView
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -05008from core.models import *
9from django.forms import widgets
Scott Baker46b58542014-08-11 17:26:12 -070010from rest_framework import filters
Scott Baker8ffd7d72014-11-10 15:58:58 -080011from django.conf.urls import patterns, url
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -050012
13"""
Sapan Bhatia970beb52014-10-08 11:34:23 -040014 Schema of the generator object:
15 all: Set of all Model objects
16 all_if(regex): Set of Model objects that match regex
Scott Bakerc480fb22014-11-12 01:12:28 -080017
Sapan Bhatia970beb52014-10-08 11:34:23 -040018 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 Bhatia3bbf5ed2014-01-13 13:29:12 -050023
Sapan Bhatia970beb52014-10-08 11:34:23 -040024 TODO: Deal with subnets
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -050025"""
26
Scott Baker8ffd7d72014-11-10 15:58:58 -080027def 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'),
Scott Bakerc480fb22014-11-12 01:12:28 -080033# url(r'plstackapi/{{ object.rest_name }}/!new/$', {{ object.camel }}New.as_view(), name ='{{ object.singular }}-new'),
Scott Baker8ffd7d72014-11-10 15:58:58 -080034 {% endfor %}
35 )
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -050036
37@api_view(['GET'])
38def api_root(request, format=None):
39 return Response({
Sapan Bhatia970beb52014-10-08 11:34:23 -040040 {% for object in generator.all %}'{{ object.plural }}': reverse('{{ object }}-list', request=request, format=format),
41 {% endfor %}
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -050042 })
43
44# Based on serializers.py
45
46{% for object in generator.all %}
47
48class {{ object.camel }}Serializer(serializers.HyperlinkedModelSerializer):
Sapan Bhatia970beb52014-10-08 11:34:23 -040049 id = serializers.Field()
50 {% for ref in object.refs %}
51 {% if ref.multi %}
52 {{ ref.plural }} = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='{{ ref }}-detail')
53 {% else %}
54 {{ ref }} = serializers.HyperlinkedRelatedField(read_only=True, view_name='{{ ref }}-detail')
55 {% endif %}
56 {% endfor %}
Scott Baker196ffef2014-11-21 11:32:24 -080057 humanReadableName = serializers.SerializerMethodField("getHumanReadableName")
58 def getHumanReadableName(self, obj):
59 return str(obj)
Sapan Bhatia970beb52014-10-08 11:34:23 -040060 class Meta:
61 model = {{ object.camel }}
Scott Baker196ffef2014-11-21 11:32:24 -080062 fields = ('humanReadableName', {% 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
64class {{ object.camel }}IdSerializer(serializers.ModelSerializer):
Sapan Bhatia970beb52014-10-08 11:34:23 -040065 id = serializers.Field()
66 {% for ref in object.refs %}
67 {% if ref.multi %}
68 {{ ref.plural }} = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='{{ ref }}-detail')
69 {% else %}
70 {{ ref }} = serializers.HyperlinkedRelatedField(read_only=True, view_name='{{ ref }}-detail')
71 {% endif %}
72 {% endfor %}
Scott Baker196ffef2014-11-21 11:32:24 -080073 humanReadableName = serializers.SerializerMethodField("getHumanReadableName")
74 def getHumanReadableName(self, obj):
75 return str(obj)
Sapan Bhatia970beb52014-10-08 11:34:23 -040076 class Meta:
77 model = {{ object.camel }}
Scott Baker196ffef2014-11-21 11:32:24 -080078 fields = ('humanReadableName', {% 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 -070079
80
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -050081{% endfor %}
82
83serializerLookUp = {
84{% for object in generator.all %}
85 {{ object.camel }}: {{ object.camel }}Serializer,
86{% endfor %}
87 None: None,
88 }
89
Scott Bakerdcb9b5d2014-10-07 00:10:17 -070090class PlanetStackRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
91
92 # To handle fine-grained field permissions, we have to check can_update
93 # the object has been updated but before it has been saved.
94
95 def update(self, request, *args, **kwargs):
96 partial = kwargs.pop('partial', False)
97 self.object = self.get_object_or_none()
98
99 serializer = self.get_serializer(self.object, data=request.DATA,
100 files=request.FILES, partial=partial)
101
102 if not serializer.is_valid():
103 print "UpdateModelMixin: not serializer.is_valid"
104 print serializer.errors
105 return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
106
107 try:
108 self.pre_save(serializer.object)
109 except ValidationError as err:
110 # full_clean on model instance may be called in pre_save,
111 # so we have to handle eventual errors.
112 return Response(err.message_dict, status=status.HTTP_400_BAD_REQUEST)
113
114 if serializer.object is not None:
115 if not serializer.object.can_update(request.user):
116 return Response(status=status.HTTP_400_BAD_REQUEST)
117
118 if self.object is None:
119 self.object = serializer.save(force_insert=True)
120 self.post_save(self.object, created=True)
121 return Response(serializer.data, status=status.HTTP_201_CREATED)
122
123 self.object = serializer.save(force_update=True)
124 self.post_save(self.object, created=False)
125 return Response(serializer.data, status=status.HTTP_200_OK)
126
127 def destroy(self, request, *args, **kwargs):
128 obj = self.get_object()
129 if obj.can_update(request.user):
Scott Bakerde12f092014-10-09 11:09:15 -0700130 return super(generics.RetrieveUpdateDestroyAPIView, self).destroy(request, *args, **kwargs)
Scott Bakerdcb9b5d2014-10-07 00:10:17 -0700131 else:
132 return Response(status=status.HTTP_400_BAD_REQUEST)
133
134
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500135# Based on core/views/*.py
136{% for object in generator.all %}
137
138class {{ object.camel }}List(generics.ListCreateAPIView):
Sapan Bhatiadf2b49e2014-01-28 19:41:07 -0500139 queryset = {{ object.camel }}.objects.select_related().all()
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500140 serializer_class = {{ object.camel }}Serializer
Scott Baker9a270922014-07-03 18:01:30 -0700141 id_serializer_class = {{ object.camel }}IdSerializer
Scott Baker46b58542014-08-11 17:26:12 -0700142 filter_backends = (filters.DjangoFilterBackend,)
143 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 -0700144
145 def get_serializer_class(self):
146 no_hyperlinks = self.request.QUERY_PARAMS.get('no_hyperlinks', False)
147 if (no_hyperlinks):
148 return self.id_serializer_class
149 else:
150 return self.serializer_class
151
Tony Mackeb8eb312014-02-04 20:50:39 -0500152 def get_queryset(self):
Tony Mack8f04ee32014-02-05 10:27:39 -0500153 return {{ object.camel }}.select_by_user(self.request.user)
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500154
Tony Mack9525eba2014-02-05 10:57:21 -0500155 def create(self, request, *args, **kwargs):
Scott Bakerc480fb22014-11-12 01:12:28 -0800156 serializer = self.get_serializer(data=request.DATA, files=request.FILES)
157 if not (serializer.is_valid()):
158 raise Exception("failed serializer.is_valid: " + str(serializer.errors))
159 obj = serializer.object
Scott Bakerde12f092014-10-09 11:09:15 -0700160 obj.caller = request.user
161 if obj.can_update(request.user):
162 return super({{ object.camel }}List, self).create(request, *args, **kwargs)
163 else:
164 raise Exception("failed obj.can_update")
165
Sapan Bhatia970beb52014-10-08 11:34:23 -0400166 ret = super({{ object.camel }}List, self).create(request, *args, **kwargs)
167 if (ret.status_code%100 != 200):
168 raise Exception(ret.data)
Scott Bakerde12f092014-10-09 11:09:15 -0700169
170 return ret
171
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500172
Scott Bakerdcb9b5d2014-10-07 00:10:17 -0700173class {{ object.camel }}Detail(PlanetStackRetrieveUpdateDestroyAPIView):
Sapan Bhatiadf2b49e2014-01-28 19:41:07 -0500174 queryset = {{ object.camel }}.objects.select_related().all()
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500175 serializer_class = {{ object.camel }}Serializer
Scott Baker46b58542014-08-11 17:26:12 -0700176 id_serializer_class = {{ object.camel }}IdSerializer
177
178 def get_serializer_class(self):
179 no_hyperlinks = self.request.QUERY_PARAMS.get('no_hyperlinks', False)
180 if (no_hyperlinks):
181 return self.id_serializer_class
182 else:
183 return self.serializer_class
Tony Mackeb8eb312014-02-04 20:50:39 -0500184
185 def get_queryset(self):
Tony Mack9525eba2014-02-05 10:57:21 -0500186 return {{ object.camel }}.select_by_user(self.request.user)
187
Scott Bakerdcb9b5d2014-10-07 00:10:17 -0700188 # update() is handled by PlanetStackRetrieveUpdateDestroyAPIView
Tony Mack9525eba2014-02-05 10:57:21 -0500189
Scott Bakerdcb9b5d2014-10-07 00:10:17 -0700190 # destroy() is handled by PlanetStackRetrieveUpdateDestroyAPIView
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500191
Scott Bakerc480fb22014-11-12 01:12:28 -0800192"""
193 XXX smbaker: my intent was to create a view that would return 'new' objects
194 filled with defaults. I solved it another way, so this code may soon be
195 abandoned.
196
197class {{ object.camel }}New(GenericAPIView):
198 serializer_class = {{ object.camel }}Serializer
199 id_serializer_class = {{ object.camel }}IdSerializer
200
201 def get(self, request, *args, **kwargs):
202 return self.makenew(request, *args, **kwargs)
203
204 def get_serializer_class(self):
205 no_hyperlinks = self.request.QUERY_PARAMS.get('no_hyperlinks', False)
206 if (no_hyperlinks):
207 return self.id_serializer_class
208 else:
209 return self.serializer_class
210
211 def makenew(self, request, *args, **kwargs):
212 obj = {{ object.camel }}()
213 serializer = self.get_serializer(obj)
214 return Response(serializer.data)
215"""
216
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500217{% endfor %}