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


    由于基础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子应用下的其它文件代码未改动,本次不再上传!

  • 相关阅读:
    11.组件-组件中的data和methods
    09.组件-创建组件的方式2
    10.组件-创建组件的方式3
    07.动画-列表动画
    08.组件-创建组件的方式1
    关于苹果iBeacon官方文档解析
    IOS-代码书写规范
    IOS- 1970ms时间计算
    关于tableview顶部留白问题
    IOS-网络请求数据解析道数组程序崩溃问题
  • 原文地址:https://www.cnblogs.com/benben-wu/p/12497446.html
Copyright © 2020-2023  润新知