django框架学习六:优化views.py文件,使用rest_framework中的APIVew和Response返回

2021-03-14 06:49

阅读:663

标签:表单   解析   文件   serial   object   elf   patch   cep   框架   

由于基础django中的View,不支持form表单传参,并且返回给前端的数据只能是json数据,所以本次优化,继承rest_framework中的APIView
请求实例方法中的第二个参数request为rest_framework中的Request对象:
request会根据请求头中的Content-Type自动解析
使用request.data可以对POST、PUT、PATCH的请求体参数进行解析,不仅支持form传参,也支持json格式传参
使用request.query_params获取查询字符串参数

views.py文件优化后的代码如下:

from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response

from django.http import Http404

from .models import Projects
from .serializers import ProjectsModelSerializer


class ProjectsList(APIView):
    def get(self, request):
        projects = Projects.objects.all()
        serializer = ProjectsModelSerializer(projects, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def post(self, request):
        serializer = ProjectsModelSerializer(data=request.data)
        try:
            serializer.is_valid(raise_exception=True)
        except Exception as e:
            return Response(serializer.errors)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)


class ProjectsDetail(APIView):
    def get_object(self, pk):
        try:
            return Projects.objects.get(id=pk)
        except Projects.DoesNotExist:
            raise Http404

    def get(self, request, pk):
        project = self.get_object(pk)
        serialzer = ProjectsModelSerializer(project)
        return Response(serialzer.data, status=status.HTTP_200_OK)

    def put(self, request, pk):
        project = self.get_object(pk)
        serialzer = ProjectsModelSerializer(instance=project, data=request.data)
        try:
            serialzer.is_valid(raise_exception=True)
        except:
            return Response(serialzer.errors)
        serialzer.save()
        return Response(serialzer.data, status=status.HTTP_201_CREATED)

    def delete(self, pk):
        project = self.get_object(pk)
        project.delete()
        return Response(None, status=status.HTTP_204_NO_CONTENT)

projects子应用下的其它文件代码未改动,本次不再上传!

django框架学习六:优化views.py文件,使用rest_framework中的APIVew和Response返回

标签:表单   解析   文件   serial   object   elf   patch   cep   框架   

原文地址:https://www.cnblogs.com/benben-wu/p/12497446.html


评论


亲,登录后才可以留言!