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 |
| 5 | from core.models import * |
| 6 | from django.forms import widgets |
| 7 | |
| 8 | """ |
| 9 | Schema of the generator object: |
| 10 | all: Set of all Model objects |
| 11 | all_if(regex): Set of Model objects that match regex |
| 12 | |
| 13 | Model object: |
| 14 | plural: English plural of object name |
| 15 | camel: CamelCase version of object name |
| 16 | refs: list of references to other Model objects |
Sapan Bhatia | 86db4df | 2014-01-14 21:18:07 -0500 | [diff] [blame] | 17 | props: list of properties minus refs |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 18 | |
| 19 | TODO: Deal with subnets |
| 20 | """ |
| 21 | |
| 22 | # Based on api_root.py |
| 23 | |
| 24 | @api_view(['GET']) |
| 25 | def api_root(request, format=None): |
| 26 | return Response({ |
Sapan Bhatia | 86db4df | 2014-01-14 21:18:07 -0500 | [diff] [blame] | 27 | {% for object in generator.all %}'{{ object.plural }}': reverse('{{ object }}-list', request=request, format=format), |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 28 | {% endfor %} |
| 29 | }) |
| 30 | |
| 31 | # Based on serializers.py |
| 32 | |
| 33 | {% for object in generator.all %} |
| 34 | |
| 35 | class {{ object.camel }}Serializer(serializers.HyperlinkedModelSerializer): |
| 36 | id = serializers.Field() |
| 37 | {% for ref in object.refs %} |
Sapan Bhatia | 86db4df | 2014-01-14 21:18:07 -0500 | [diff] [blame] | 38 | {{ ref.plural }} = serializers.HyperlinkedRelatedField(view_name='{{ ref }}-detail') |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 39 | {% endfor %} |
| 40 | class Meta: |
| 41 | model = {{ object }} |
Sapan Bhatia | 86db4df | 2014-01-14 21:18:07 -0500 | [diff] [blame] | 42 | fields = ({% for prop in object.props %}'{{ prop }}',{% endfor %}) |
Sapan Bhatia | 3bbf5ed | 2014-01-13 13:29:12 -0500 | [diff] [blame] | 43 | {% endfor %} |
| 44 | |
| 45 | serializerLookUp = { |
| 46 | {% for object in generator.all %} |
| 47 | {{ object.camel }}: {{ object.camel }}Serializer, |
| 48 | {% endfor %} |
| 49 | None: None, |
| 50 | } |
| 51 | |
| 52 | # Based on core/views/*.py |
| 53 | {% for object in generator.all %} |
| 54 | |
| 55 | class {{ object.camel }}List(generics.ListCreateAPIView): |
| 56 | queryset = {{ object.camel }}.objects.all() |
| 57 | serializer_class = {{ object.camel }}Serializer |
| 58 | |
| 59 | class {{ object.camel }}Detail(generics.RetrieveUpdateDestroyAPIView): |
| 60 | queryset = {{ object.camel }}.objects.all() |
| 61 | serializer_class = {{ object.camel }}Serializer |
| 62 | |
| 63 | {% endfor %} |