Django前后端分离实践之DRF--05

一、基于类的视图(CBV)

1. 导入模块

from rest_framework.views import APIView

2. GET

from .models import Publisher
from app01 import serializers
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView


class PublisherList(APIView):
    """
    列出所有的出版,get
    或者创建一个新的出版社post
    """

    def get(self, request, format=None):
        queryset = Publisher.objects.all()  # 查询出所有出版社
        s = serializers.PublisherSerializer(queryset, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

2. POST

    def post(self,request,format=None):
        s = serializers.PublisherSerializer(data=request.data)
        if s.is_valid():
            s.save()
            return Response(s.data,status=status.HTTP_201_CREATED)
        else:
            return Response(s.errors,status=status.HTTP_400_BAD_REQUEST)

[站外图片上传中...(image-58db01-1540132721236)]

4. 具体的某一个出版社CBV

class PublisherDetail(APIView):
    """
    具体的某一个出版社  查看.修改.删除的视图
    """

    # 需要先尝试的从数据库查到 pk对应的数据,如果没有返回404
    def get_object(self, pk):
        try:
            return Publisher.objects.get(pk=pk)
        except Publisher.DoesNotExist:
            raise Http404 # 需要先导入 from django.http import Http404
  • GET 获取出版社信息(单个)
 def get(self, request, pk, format=None):
        publisher = self.get_object(pk)
        s = serializers.PublisherSerializer(publisher)
        return Response(s.data, status=status.HTTP_200_OK)
  • PUT 修改出版社信息(单个)
    def put(self, request, pk, format=None):
        publisher = self.get_object(pk)
        s = serializers.PublisherSerializer(publisher, data=request.data)
        if s.is_valid():
            s.save()
            return Response(s.data)
        else:
            Response(s.errors, status=status.HTTP_400_BAD_REQUEST)

[站外图片上传中...(image-9b7a91-1540132721236)]

  • DELETE  删除出版社信息(单个)
    def delete(self, request, pk, format=None):
        """删除出版社信息"""
        publisher = self.get_object(pk)
        publisher.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

5. 修改url

url(r'^publishers/$', views.PublisherList.as_view()),
url(r'^publishers/(?P<pk>[0-9]+)/$', views.PublisherDetail.as_view()),

[站外图片上传中...(image-f8ff24-1540132721236)]

二、使用混合(mixins)

使用基于类视图的最大优势之一是它可以轻松地创建可复用的行为。

到目前为止,我们使用的创建/获取/更新/删除操作和我们创建的任何基于模型的API视图非常相似。这些常见的行为是在REST框架的mixin类中实现的。

1.导入模块

from rest_framework import mixins
from rest_framework import generics

2.编写视图

from rest_framework import mixins
from rest_framework import generics


class PublisherList(mixins.ListModelMixin,
                    mixins.CreateModelMixin,
                    generics.GenericAPIView):
    queryset = Publisher.objects.all()
    serializers_class = serializers.PublisherSerializer

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)
img_e799252bbfe32705a1763eb7808412e2.png
选区_191
class PublisherDetail(mixins.RetrieveModelMixin,
                      mixins.UpdateModelMixin,
                      mixins.DestroyModelMixin,
                      generics.GenericAPIView):

    queryset = Publisher.objects.all()
    serializer_class = serializers.PublisherSerializer

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)
  • 刷新浏览器
img_eb9ef7df40dbfbec97d4194eebcabb76.png
选区_192

3.改进混合视图

class PublisherList(generics.ListCreateAPIView):
    queryset = Publisher.objects.all()
    serializer_class = serializers.PublisherSerializer
class PublisherDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Publisher.objects.all()
    serializer_class = serializers.PublisherSerializer
  • 刷新浏览器

[站外图片上传中...(image-de040b-1540132721236)]

[站外图片上传中...(image-b4dc28-1540132721236)]

4. 此时我们观察,代码已经精简至3行

官方文档一句话说的非常好:仅仅只需要很少的几行代码,就可以完成非常清晰,简洁,地道的Django

[站外图片上传中...(image-401930-1540132721236)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值