• DRF--view


    在学django的时候,我们写视图是这样的

    from django.http import HttpResponse, JsonResponse
    from django.views.decorators.csrf import csrf_exempt
    from rest_framework.renderers import JSONRenderer
    from rest_framework.parsers import JSONParser
    from snippets.models import Snippet
    from snippets.serializers import SnippetSerializer
    
    
    @csrf_exempt  # 这个函数可以跨域访问
    def snippet_list(request):
        if request.method == 'GET':  # get请求
            snippets = Snippet.objects.all()
            serializer = SnippetSerializer(snippets, many=True)  # 序列化
            return JsonResponse(serializer.data, safe=False)
    
        if request.method == 'POST':  # post请求
            data = JSONParser().parse(request)
            serializer = SnippetSerializer(data=data)  # 序列化
            if serializer.is_valid():  # 验证序列化
                serializer.save()  # 保持数据
                return JsonResponse(serializer.data, status=201)
            return JsonResponse(serializer.errors, status=400)
    
    
    @csrf_exempt
    def snippet_detail(request, pk):  # 获取单个数据
        try:
            snippet = Snippet.objects.get(pk=pk)  # ORM的模型的对象,一个
        except Snippet.DoesNotExist:
            return HttpResponse(status=404)
    
        if request.method == 'GET':  # 获取单个数据
            serializer = SnippetSerializer(snippet)
            return JsonResponse(serializer.data)
    
        if request.method == 'PUT':  # 修改单个数据
            data = JSONParser().parse(request)
            serializer = SnippetSerializer(snippet, data=data)
            if serializer.is_valid():
                serializer.save()
                return JsonResponse(serializer.data)
            return JsonResponse(serializer.errors, status=400)
    
        if request.method == 'DELETE':  # 删除单个数据
            snippet.delete()
            return HttpResponse(status=204)

    第二版

    from rest_framework import status
    from rest_framework.decorators import api_view
    from rest_framework.response import Response
    from snippets.models import Snippet
    from snippets.serializers import SnippetSerializer
    
    
    @api_view(['GET', "POST"])  # get和post可以访问
    def snippet_list(request, format=None):
        if request.method == 'GET':  # get对应的方法,获取全部数据
            snippets = Snippet.objects.all()
            serializer = SnippetSerializer(snippets, many=True)
            return Response(serializer.data)
    
        if request.method == 'POST':  # post对应的方法
            serializer = SnippetSerializer(data=request.data)
            if serializer.is_valid():  # validated_data
                serializer.save()  # ORM,保存到数据库中
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    
    @api_view(['GET', 'PUT', 'DELETE'])  # 获取单个数据,put,delete对应的方法
    def snippet_detail(request, pk, format=None):
        try:
            snippet = Snippet.objects.get(pk=pk)  # ORM的模型的对象,一个
        except Snippet.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
    
        if request.method == 'GET':  # 获取单条数据
            serializer = SnippetSerializer(snippet)
            return Response(serializer.data)
    
        if request.method == 'PUT':  # 修改数据
            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)
    
        if request.method == 'DELETE':  # 删除数据
            snippet.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)

    第三版,使用APIView

    from snippets.models import Snippet
    from snippets.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
    
    
    class SnippetList(APIView):  # 继承APIView
    
        def get(self, request, format=None):  # get请求获取所有数据
            snippets = Snippet.objects.all()  # 查询数据
            serializer = SnippetSerializer(snippets, many=True)  # 序列化
            return Response(serializer.data)
    
        def post(self, request, format=None):  # post请求
            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)
    
    
    class SnippetDetail(APIView):
    
        def get_object(self, pk):
            try:
                snippet = Snippet.objects.get(pk=pk)  # ORM的模型的对象,一个
                return snippet
            except Snippet.DoesNotExist:
                raise Http404
    
        def get(self, request, pk, format=None):  # 获取单条数据
            snippet = self.get_object(pk)
            serializer = SnippetSerializer(snippet)
            return Response(serializer.data)
    
        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)
    
        def delete(self, request, pk, format=None):  # 删除数据
            snippet = self.get_object(pk)
            snippet.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)

    第四版,混入mixin

    from snippets.models import Snippet
    from snippets.serializers import SnippetSerializer
    from rest_framework import mixins  # 导入mixins
    from rest_framework import generics  # 导入generics
    
    
    # ListModelMixin获取所有数据,CreateModelMixin创建数据
    class SnippetList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
        queryset = Snippet.objects.all()  # filter()
        serializer_class = SnippetSerializer  # 序列化对象
    
        def get(self, request, *args, **kwargs):
            # 调用ListModelMixin下的list方法,获取所有数据
            return self.list(request, *args, **kwargs)
    
        def post(self, request, *args, **kwargs):
            # 调用CreateModelMixin下的create方法,添加数据
            return self.create(request, *args, **kwargs)
    
    
    
    # RetrieveModelMixin获取单条数据,UpdateModelMixin修改数据,DestroyModelMixin删除数据
    class SnippetDetail(mixins.RetrieveModelMixin,
                        mixins.UpdateModelMixin,
                        mixins.DestroyModelMixin,
                        generics.GenericAPIView):
        queryset = Snippet.objects.all()  # filter()
        serializer_class = SnippetSerializer
    
        def get(self, request, *args, **kwargs):
            # 调用RetrieveModelMixin下的retrieve方法,获取单条数据
            return self.retrieve(request, *args, **kwargs)
    
        def put(self, request, *args, **kwargs):
            # 调用UpdateModelMixin下的update方法,修改数据
            return self.update(request, *args, **kwargs)
    
        def delete(self, request, *args, **kwargs):
            # 调用DestroyModelMixin下的destroy方法,删除数据
            return self.destroy(request, *args, **kwargs)

    第五版,上面的在简化

    from snippets.models import Snippet
    from snippets.serializers import SnippetSerializer
    from rest_framework import generics
    from rest_framework import permissions
    from snippets.permissions import IsOwnerOrReadOnly
    
    
    
    # generics.ListCreateAPIView继承了mixins.ListModelMixin, mixins.CreateModelMixin, GenericAPIView
    # 获取所有数据(List),添加数据(Create)
    class SnippetList(generics.ListCreateAPIView):
        queryset = Snippet.objects.all()
        serializer_class = SnippetSerializer
    
        def perform_create(self, serializer):
            serializer.save(owner=self.request.user)
    
    
    # generics.RetrieveUpdateDestroyAPIView继承了mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin
    # 获取单个数据(Retrieve),修改数据(Update),删除数据(Destroy)
    class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
        # 当获取单个数据,修改数据,删除数据的时候,就去父类RetrieveUpdateDestroyAPIView找
        queryset = Snippet.objects.all()
        serializer_class = SnippetSerializer
  • 相关阅读:
    WPFlog4net学习笔记(一)
    C#比较两个List是否相同_SequenceEqual
    01.HTML基础
    startActivityForResult()被标注弃用,推荐使用registerForActivityResult()方法
    02.Android项目介绍
    07.活动的生命周期
    03.活动Activity
    06.通过意图传递数据
    04.Toast、Menu、销毁活动
    05.显式意图、隐式意图
  • 原文地址:https://www.cnblogs.com/zouzou-busy/p/12051189.html
Copyright © 2020-2023  润新知