This repository has been archived on 2022-09-23. You can view files and clone it, but cannot push or open issues or pull requests.
webdev/website/snippets/views.py

51 lines
1.7 KiB
Python
Raw Normal View History

2022-01-08 00:12:34 +01:00
from .models import Snippet
from .serializers import SnippetSerializer
2022-01-08 00:28:32 +01:00
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
2022-01-08 00:12:34 +01:00
2022-01-08 00:28:32 +01:00
class SnippetList(APIView):
2022-01-08 00:12:34 +01:00
"""
2022-01-08 00:28:32 +01:00
List all snippets, or create a new snippet.
2022-01-08 00:12:34 +01:00
"""
2022-01-08 00:28:32 +01:00
def get(self, request, format=None):
2022-01-08 00:12:34 +01:00
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
2022-01-08 00:24:32 +01:00
return Response(serializer.data)
2022-01-08 00:12:34 +01:00
2022-01-08 00:28:32 +01:00
def post(self, request, format=None):
2022-01-08 00:24:32 +01:00
serializer = SnippetSerializer(data=request.data)
2022-01-08 00:12:34 +01:00
if serializer.is_valid():
serializer.save()
2022-01-08 00:24:32 +01:00
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
2022-01-08 00:12:34 +01:00
2022-01-08 00:28:32 +01:00
class SnippetDetail(APIView):
2022-01-08 00:12:34 +01:00
"""
2022-01-08 00:28:32 +01:00
Retrieve, update or delete a snippet instance.
2022-01-08 00:12:34 +01:00
"""
2022-01-08 00:28:32 +01:00
def get_object(self, pk):
try:
return Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
raise Http404
2022-01-08 00:12:34 +01:00
2022-01-08 00:28:32 +01:00
def get(self, request, pk, format=None):
snippet = self.get_object(pk)
2022-01-08 00:12:34 +01:00
serializer = SnippetSerializer(snippet)
2022-01-08 00:24:32 +01:00
return Response(serializer.data)
2022-01-08 00:12:34 +01:00
2022-01-08 00:28:32 +01:00
def put(self, request, pk, format=None):
snippet = self.get_object(pk)
2022-01-08 00:24:32 +01:00
serializer = SnippetSerializer(snippet, data=request.data)
2022-01-08 00:12:34 +01:00
if serializer.is_valid():
serializer.save()
2022-01-08 00:24:32 +01:00
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
2022-01-08 00:12:34 +01:00
2022-01-08 00:28:32 +01:00
def delete(self, request, pk, format=None):
snippet = self.get_object(pk)
2022-01-08 00:12:34 +01:00
snippet.delete()
2022-01-08 00:24:32 +01:00
return Response(status=status.HTTP_204_NO_CONTENT)