REST framework提供了一个APIView类,它是Django的View类的子类。
APIView类和一般的View类有以下不同:
- 被传入到处理方法的请求不会是Django的HttpRequest类的实例,而是REST framework的Request类的实例。
- 处理方法可以返回REST framework的Response,而不是Django的HttpRequest。视图会管理内容协议,给响应设置正确的渲染器。
- 任何APIException异常都会被捕获,并且传递给合适的响应。
- 进入的请求将会经过认证,合适的权限和(或)节流检查会在请求被派发到处理方法之前运行。
使用APIView类和使用一般的View类非常相似,通常,进入的请求会被分发到合适处理方法比如.get(),或者.post。另外,很多属性会被设定在控制API策略的各种切面的类上。
打开project\views.py
,让我们用代码感受下
from django.http import JsonResponse, Http404
from .models import Projects
from .serializers import ProjectsModelSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class ProjectView(APIView):
# 查询所有数据
def get(self, request):
projects_obj = Projects.objects.all()
serializer_obj = ProjectsModelSerializer(instance=projects_obj, many=True)
return Response(serializer_obj.data, status=status.HTTP_200_OK)
def post(self, request):
# request.data:从request中获取请求数据
serializer_obj = ProjectsModelSerializer(data=request.data)
# 调用is_valid(raise_exception=True),校验失败时抛出异常
serializer_obj.is_valid(raise_exception=True)
serializer_obj.save()
return Response(serializer_obj.data, status=status.HTTP_201_CREATED)
class ProjectDetailView(APIView):
# 查询单个数据
def get(self, request, pk):
try:
project_obj = Projects.objects.get(id=pk)
except Projects.DoesNotExist:
raise Http404
serializer_obj = ProjectsModelSerializer(instance=project_obj)
return Response(serializer_obj.data, status=status.HTTP_200_OK)
# 更新数据
def put(self, request, pk):
try:
project_obj = Projects.objects.get(id=pk)
except Projects.DoesNotExist:
raise Http404
serializer_obj = ProjectsModelSerializer(data=request.data, instance=project_obj)
# 调用is_valid(raise_exception=True),校验失败时抛出异常
serializer_obj.is_valid(raise_exception=True)
serializer_obj.save()
return JsonResponse(serializer_obj.data, status=status.HTTP_201_CREATED)
# 删除数据
def delete(self, request, pk):
try:
project_obj = Projects.objects.get(id=pk)
except Projects.DoesNotExist:
raise Http404
project_obj.delete()
return Response(data={"msg": "刪除成功"}, status=status.HTTP_204_NO_CONTENT)
ok,我们继续用postman测试下。测试过程省略。