视图

基于APIView写接口

# views.py
# 基于APIView写的
# class BookView(APIView):
#     def get(self, request):
#         book_list = Book.objects.all()
#         book_ser = BookSerializer(book_list, many=True)
#         return Response(book_ser.data)
#
#     def post(self, request):
#         book_ser = BookSerializer(data=request.data)
#         if book_ser.is_valid():
#             book_ser.save()
#             return Response(book_ser.data)
#         else:
#             return Response({'status': 101, 'msg': '校验失败'})
#
#
# class BookDataView(APIView):
#     def get(self, request, pk):
#         book = Book.objects.all().filter(pk=pk).first()
#         book_ser = BookSerializer(book)
#         return Response(book_ser.data)
#
#     def put(self, request, pk):
#         print(pk)
#         book = Book.objects.filter(pk=pk).first()
#         book_ser = BookSerializer(instance=book, data=request.data)
#         if book_ser.is_valid():
#             book_ser.save()
#             return Response(book_ser.data)
#         else:
#             return Response({'status': 101, 'msg': '校验失败'})
#
#     def delete(self,request,pk):
#         ret = Book.objects.filter(pk=pk).delete()
#         return Response({'status': 100, 'msg': '删除成功'})


# models.py:
from django.db import models

# Create your models here.

class Book(models.Model):
    name = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=5,decimal_places=2)
    publish = models.CharField(max_length=32)
    
# ser.py
from rest_framework import serializers
from app01.models import Book


class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'
        
# urls.py:
    path('books/', views.BookView.as_view()),
    re_path('books/(?P<pk>\d+)', views.BookDataView.as_view()),

 

基于GenericAPIView写的接口

# views.py:
# 基于GenericAPIView写的

class BookView(GenericAPIView):
    # queryset要传queryset对象,查询了所有的图书
    # serializer_class使用了哪个序列化类来序列化这堆数据
    # queryset = Book.objects.all()
    queryset = Book.objects
    serializer_class = BookSerializer

    def get(self, request):
        book_list = self.get_queryset()
        book_ser = self.get_serializer(book_list, many=True)
        return Response(book_ser.data)

    def post(self, request):
        book_ser = self.get_serializer(data=request.data)
        if book_ser.is_valid():
            book_ser.save()
            return Response(book_ser.data)
        else:
            return Response({'status': 101, 'msg': '校验失败'})


class BookDataView(GenericAPIView):
    queryset = Book.objects
    serializer_class = BookSerializer

    def get(self, request, pk):
        book = self.get_object()
        book_ser = self.get_serializer(book)
        return Response(book_ser.data)

    def put(self, request, pk):
        print(pk)
        book = self.get_object()
        book_ser = self.get_serializer(instance=book, data=request.data)
        if book_ser.is_valid():
            book_ser.save()
            return Response(book_ser.data)
        else:
            return Response({'status': 101, 'msg': '校验失败'})

    def delete(self, request, pk):
        ret = self.get_object().delete()
        return Response({'status': 100, 'msg': '删除成功'})

# urls.py:
    # 使用GenericAPIView重写的
    path('books/', views.BookView.as_view()),
    re_path('books/(?P<pk>\d+)', views.BookDataView.as_view()),

 

基于GenericAPIView和五个视图扩展类写的接口

from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, \
    DestroyModelMixin

 

# views.py:
class BookListView(ListModelMixin, GenericAPIView, CreateModelMixin):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    def get(self, request):
        return self.list(request)

    def post(self, request):
        return self.create(request)


class Book3DetailView(GenericAPIView, RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    def get(self, request, pk):
        return self.retrieve(request, pk)

    def put(self, request, pk):
        return self.update(request, pk)

    def delete(self, request, pk):
        return self.destroy(request, pk)

 

GenericAPIView的视图子类

# views.py:
# 使用ModelViewSet编写5个接口
from rest_framework.viewsets import ModelViewSet

class Book5View(ModelViewSet):  # 5个接口都有,但是路由有点问题
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    
   
# urls.py:
# 使用ModelViewSet编写5个接口
    path('books5/', views.Book5View.as_view(actions={'get': 'list', 'post': 'create'})),
    re_path('books5/(?P<pk>\d+)',
            views.Book5View.as_view(actions={'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),

 

源码分析ViewSetMixin

# 重写了as_view
# 核心代码(所以说路由中只要配置了对应关系,比如{'get':'list'},当get请求来,就会执行list方法
    for method, action in actions.items():
        # method:get
        # action:list
        handler = getattr(self, action)
        # 执行完上一句,handler就变成了list的内存地址
        setattr(self, method, handler)
        # 执行完上一句 对象.get=list
        # for循环完毕 对象.get:对着list  对象.post:对着create

 

继承ViewSetMixin的视图类

# views.py:
from rest_framework.viewsets import ViewSetMixin

class Book6View(ViewSetMixin, APIView):  # 一定要放在APIView前面,继承的顺序:先找自己的,然后再从第一个父类中找,再找后面的,先执行谁就把谁放前面
    def get_all_book(self, request):
        print('执行了这个')
        book_list = Book.objects.all()
        book_ser = BookSerializer(book_list, many=True)
        return Response(book_ser.data)

 
# urls.py:
    # 继承ViewSetMixin的视图类,路由可以改写成这样
    path('books6/', views.Book6View.as_view(actions={'get': 'get_all_book'})),

 

 

 

posted @ 2021-06-11 17:05  Palpitate~  阅读(30)  评论(0编辑  收藏  举报