Tony Mack | 29c287f | 2013-04-11 21:07:16 -0400 | [diff] [blame] | 1 | from django.http import Http404 |
| 2 | from rest_framework.views import APIView |
| 3 | from rest_framework.response import Response |
| 4 | from rest_framework import status |
| 5 | |
| 6 | from plstackapi.core.api.subnets import add_subnet, delete_subnet, get_subnets, update_subnet |
| 7 | from plstackapi.core.serializers import SubnetSerializer |
| 8 | from plstackapi.util.request import parse_request |
| 9 | |
| 10 | |
| 11 | class SubnetListCreate(APIView): |
| 12 | """ |
| 13 | List all subnets or create a new subnet. |
| 14 | """ |
| 15 | |
| 16 | def post(self, request, format = None): |
| 17 | data = parse_request(request.DATA) |
| 18 | if 'auth' not in data: |
| 19 | return Response(status=status.HTTP_400_BAD_REQUEST) |
| 20 | elif 'subnet' in data: |
| 21 | subnet = add_subnet(data['auth'], data['subnet']) |
| 22 | serializer = SubnetSerializer(subnet) |
| 23 | return Response(serializer.data, status=status.HTTP_201_CREATED) |
| 24 | else: |
| 25 | subnets = get_subnets(data['auth']) |
| 26 | serializer = SubnetSerializer(subnets, many=True) |
| 27 | return Response(serializer.data) |
| 28 | |
| 29 | |
| 30 | class SubnetRetrieveUpdateDestroy(APIView): |
| 31 | """ |
| 32 | Retrieve, update or delete a subnet |
| 33 | """ |
| 34 | |
| 35 | def post(self, request, pk, format=None): |
| 36 | """Retrieve a subnet""" |
| 37 | data = parse_request(request.DATA) |
| 38 | if 'auth' not in data: |
| 39 | return Response(status=status.HTTP_400_BAD_REQUEST) |
| 40 | subnets = get_subnets(data['auth'], {'id': pk}) |
| 41 | if not subnets: |
| 42 | return Response(status=status.HTTP_404_NOT_FOUND) |
| 43 | serializer = SubnetSerializer(subnets[0]) |
| 44 | return Response(serializer.data) |
| 45 | |
| 46 | def put(self, request, pk, format=None): |
| 47 | """update a subnet""" |
| 48 | data = parse_request(request.DATA) |
| 49 | if 'auth' not in data: |
| 50 | return Response(status=status.HTTP_400_BAD_REQUEST) |
| 51 | elif 'subnet' not in data: |
| 52 | return Response(status=status.HTTP_400_BAD_REQUEST) |
| 53 | |
| 54 | subnet = update_subnet(pk, data['subnet']) |
| 55 | serializer = SubnetSerializer(subnet) |
| 56 | return Response(serializer.data) |
| 57 | |
| 58 | def delete(self, request, pk, format=None): |
| 59 | data = parse_request(request.DATA) |
| 60 | if 'auth' not in data: |
| 61 | return Response(status=status.HTTP_400_BAD_REQUEST) |
| 62 | delete_subnet(data['auth'], {'id': pk}) |
| 63 | return Response(status=status.HTTP_204_NO_CONTENT) |
| 64 | |
| 65 | |
| 66 | |