restful介面設計的示例
from rest_framework.request import Request
from rest_framework.response import Response
from .serializers import BookModelSerializer
from .models import BookInfo
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from rest_framework import generics
from rest_framework import mixins
from rest_framework import viewsets
# books/==>
class BooksAPIView(APIView):
def get(self, request):
blist = BookInfo.objects.all()
book_serializer = BookModelSerializer(blist, many=True)
return Response(book_serializer.data)
def post(self, request):
data = request.data
book_serializer = BookModelSerializer(data=data)
if book_serializer.is_valid():
book = book_serializer.save()
book_serializer = BookModelSerializer(book)
return Response(book_serializer.data)
else:
print(book_serializer.errors)
return Response(status=status.HTTP_400_BAD_REQUEST)
# books/pk==>
class BookAPIView(APIView):
def get(self, request, pk):
book = BookInfo.objects.get(pk=pk)
book_serializer = BookModelSerializer(book)
return Response(book_serializer.data)
def put(self, request, pk):
'''
修改物件,引數需要指定所有屬性
'''
pass
def patch(self, request, pk):
'''
修改物件,引數指定修改的屬性
'''
pass
def delete(self, request, pk):
pass
class BooksGenericAPIView(generics.ListCreateAPIView):
# (
# mixins.ListModelMixin,
# mixins.CreateModelMixin,
# GenericAPIView):
queryset = BookInfo.objects.all()
serializer_class = BookModelSerializer
def get(self, request):
return self.list(request)
# blist = self.get_queryset()
# book_serializer = self.get_serializer(blist, many=True)
# return Response(book_serializer.data)
def post(self, request):
return self.create(request)
class BookGenericAPIView(generics.RetrieveUpdateDestroyAPIView):
# (
# mixins.RetrieveModelMixin,
# mixins.UpdateModelMixin,
# mixins.DestroyModelMixin,
# GenericAPIView):
queryset = BookInfo.objects.all()
serializer_class = BookModelSerializer
def get(self, request, pk):
return self.retrieve(request)
# book = self.get_object()
# book_serializer = self.get_serializer(book)
# return Response(book_serializer.data)
def put(self, request, pk):
return self.update(request)
def patch(self, request, pk):
return self.update(request, partial=True)
def delete(self, request, pk):
return self.destroy(request)
class BookModelViewSet(viewsets.ModelViewSet):
'''
list:
查詢所有的圖書資訊
create:
建立圖書物件
'''
queryset = BookInfo.objects.all()
serializer_class = BookModelSerializer
#?title=查詢值
filter_fields=['title','bread']
#?ordering=-id
ordering_fields=['id','bread']
def get_serializer_class(self):
# print(self.request.version)
return BookModelSerializer