blob: f9d9cb82c0029c6f8ddd6e866074664a95bc5be8 [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 %}
57 class Meta:
58 model = {{ object.camel }}
59 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 -070060
61class {{ object.camel }}IdSerializer(serializers.ModelSerializer):
Sapan Bhatia970beb52014-10-08 11:34:23 -040062 id = serializers.Field()
63 {% for ref in object.refs %}
64 {% if ref.multi %}
65 {{ ref.plural }} = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='{{ ref }}-detail')
66 {% else %}
67 {{ ref }} = serializers.HyperlinkedRelatedField(read_only=True, view_name='{{ ref }}-detail')
68 {% endif %}
69 {% endfor %}
70 class Meta:
71 model = {{ object.camel }}
72 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 -070073
74
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -050075{% endfor %}
76
77serializerLookUp = {
78{% for object in generator.all %}
79 {{ object.camel }}: {{ object.camel }}Serializer,
80{% endfor %}
81 None: None,
82 }
83
Scott Bakerdcb9b5d2014-10-07 00:10:17 -070084class PlanetStackRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
85
86 # To handle fine-grained field permissions, we have to check can_update
87 # the object has been updated but before it has been saved.
88
89 def update(self, request, *args, **kwargs):
90 partial = kwargs.pop('partial', False)
91 self.object = self.get_object_or_none()
92
93 serializer = self.get_serializer(self.object, data=request.DATA,
94 files=request.FILES, partial=partial)
95
96 if not serializer.is_valid():
97 print "UpdateModelMixin: not serializer.is_valid"
98 print serializer.errors
99 return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
100
101 try:
102 self.pre_save(serializer.object)
103 except ValidationError as err:
104 # full_clean on model instance may be called in pre_save,
105 # so we have to handle eventual errors.
106 return Response(err.message_dict, status=status.HTTP_400_BAD_REQUEST)
107
108 if serializer.object is not None:
109 if not serializer.object.can_update(request.user):
110 return Response(status=status.HTTP_400_BAD_REQUEST)
111
112 if self.object is None:
113 self.object = serializer.save(force_insert=True)
114 self.post_save(self.object, created=True)
115 return Response(serializer.data, status=status.HTTP_201_CREATED)
116
117 self.object = serializer.save(force_update=True)
118 self.post_save(self.object, created=False)
119 return Response(serializer.data, status=status.HTTP_200_OK)
120
121 def destroy(self, request, *args, **kwargs):
122 obj = self.get_object()
123 if obj.can_update(request.user):
Scott Bakerde12f092014-10-09 11:09:15 -0700124 return super(generics.RetrieveUpdateDestroyAPIView, self).destroy(request, *args, **kwargs)
Scott Bakerdcb9b5d2014-10-07 00:10:17 -0700125 else:
126 return Response(status=status.HTTP_400_BAD_REQUEST)
127
128
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500129# Based on core/views/*.py
130{% for object in generator.all %}
131
132class {{ object.camel }}List(generics.ListCreateAPIView):
Sapan Bhatiadf2b49e2014-01-28 19:41:07 -0500133 queryset = {{ object.camel }}.objects.select_related().all()
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500134 serializer_class = {{ object.camel }}Serializer
Scott Baker9a270922014-07-03 18:01:30 -0700135 id_serializer_class = {{ object.camel }}IdSerializer
Scott Baker46b58542014-08-11 17:26:12 -0700136 filter_backends = (filters.DjangoFilterBackend,)
137 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 -0700138
139 def get_serializer_class(self):
140 no_hyperlinks = self.request.QUERY_PARAMS.get('no_hyperlinks', False)
141 if (no_hyperlinks):
142 return self.id_serializer_class
143 else:
144 return self.serializer_class
145
Tony Mackeb8eb312014-02-04 20:50:39 -0500146 def get_queryset(self):
Tony Mack8f04ee32014-02-05 10:27:39 -0500147 return {{ object.camel }}.select_by_user(self.request.user)
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500148
Tony Mack9525eba2014-02-05 10:57:21 -0500149 def create(self, request, *args, **kwargs):
Scott Bakerc480fb22014-11-12 01:12:28 -0800150 serializer = self.get_serializer(data=request.DATA, files=request.FILES)
151 if not (serializer.is_valid()):
152 raise Exception("failed serializer.is_valid: " + str(serializer.errors))
153 obj = serializer.object
Scott Bakerde12f092014-10-09 11:09:15 -0700154 obj.caller = request.user
155 if obj.can_update(request.user):
156 return super({{ object.camel }}List, self).create(request, *args, **kwargs)
157 else:
158 raise Exception("failed obj.can_update")
159
Sapan Bhatia970beb52014-10-08 11:34:23 -0400160 ret = super({{ object.camel }}List, self).create(request, *args, **kwargs)
161 if (ret.status_code%100 != 200):
162 raise Exception(ret.data)
Scott Bakerde12f092014-10-09 11:09:15 -0700163
164 return ret
165
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500166
Scott Bakerdcb9b5d2014-10-07 00:10:17 -0700167class {{ object.camel }}Detail(PlanetStackRetrieveUpdateDestroyAPIView):
Sapan Bhatiadf2b49e2014-01-28 19:41:07 -0500168 queryset = {{ object.camel }}.objects.select_related().all()
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500169 serializer_class = {{ object.camel }}Serializer
Scott Baker46b58542014-08-11 17:26:12 -0700170 id_serializer_class = {{ object.camel }}IdSerializer
171
172 def get_serializer_class(self):
173 no_hyperlinks = self.request.QUERY_PARAMS.get('no_hyperlinks', False)
174 if (no_hyperlinks):
175 return self.id_serializer_class
176 else:
177 return self.serializer_class
Tony Mackeb8eb312014-02-04 20:50:39 -0500178
179 def get_queryset(self):
Tony Mack9525eba2014-02-05 10:57:21 -0500180 return {{ object.camel }}.select_by_user(self.request.user)
181
Scott Bakerdcb9b5d2014-10-07 00:10:17 -0700182 # update() is handled by PlanetStackRetrieveUpdateDestroyAPIView
Tony Mack9525eba2014-02-05 10:57:21 -0500183
Scott Bakerdcb9b5d2014-10-07 00:10:17 -0700184 # destroy() is handled by PlanetStackRetrieveUpdateDestroyAPIView
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500185
Scott Bakerc480fb22014-11-12 01:12:28 -0800186"""
187 XXX smbaker: my intent was to create a view that would return 'new' objects
188 filled with defaults. I solved it another way, so this code may soon be
189 abandoned.
190
191class {{ object.camel }}New(GenericAPIView):
192 serializer_class = {{ object.camel }}Serializer
193 id_serializer_class = {{ object.camel }}IdSerializer
194
195 def get(self, request, *args, **kwargs):
196 return self.makenew(request, *args, **kwargs)
197
198 def get_serializer_class(self):
199 no_hyperlinks = self.request.QUERY_PARAMS.get('no_hyperlinks', False)
200 if (no_hyperlinks):
201 return self.id_serializer_class
202 else:
203 return self.serializer_class
204
205 def makenew(self, request, *args, **kwargs):
206 obj = {{ object.camel }}()
207 serializer = self.get_serializer(obj)
208 return Response(serializer.data)
209"""
210
Sapan Bhatia3bbf5ed2014-01-13 13:29:12 -0500211{% endfor %}