class based views

This commit is contained in:
Pratyush Desai 2022-01-08 04:58:32 +05:30
parent 01035a2b45
commit 37bf9a0c82
Signed by: pratyush
GPG Key ID: DBA5BB7505946FAD
2 changed files with 24 additions and 20 deletions

View File

@ -3,8 +3,8 @@ from rest_framework.urlpatterns import format_suffix_patterns
from . import views
urlpatterns = [
path('snippets/', views.snippet_list),
path('snippets/<int:pk>/', views.snippet_detail),
path('snippets/', views.SnippetList.as_view()),
path('snippets/<int:pk>/', views.SnippetDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)

View File

@ -1,47 +1,51 @@
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Snippet
from .serializers import SnippetSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
@api_view(['GET', 'POST'])
def snippet_list(request, format=None):
class SnippetList(APIView):
"""
List all code snippets, or create a new snippet.
List all snippets, or create a new snippet.
"""
if request.method == 'GET':
def get(self, request, format=None):
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)
elif request.method == 'POST':
def post(self, request, format=None):
serializer = SnippetSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', 'PUT', 'DELETE'])
def snippet_detail(request, pk, format=None):
class SnippetDetail(APIView):
"""
Retrieve, update or delete a code snippet.
Retrieve, update or delete a snippet instance.
"""
def get_object(self, pk):
try:
snippet = Snippet.objects.get(pk=pk)
return Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
raise Http404
if request.method == 'GET':
def get(self, request, pk, format=None):
snippet = self.get_object(pk)
serializer = SnippetSerializer(snippet)
return Response(serializer.data)
elif request.method == 'PUT':
def put(self, request, pk, format=None):
snippet = self.get_object(pk)
serializer = SnippetSerializer(snippet, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
def delete(self, request, pk, format=None):
snippet = self.get_object(pk)
snippet.delete()
return Response(status=status.HTTP_204_NO_CONTENT)