Django-RESTful Api之基于类的视图

优点

  • 把各种HTTP请求分离开,不用分支计算
  • 增加了可读性
  • 可以轻松的重复使用代码

修改视图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from myApp.models import Student, Grade
from myApp.serializers import StudentSerializer
from rest_framework.decorators import api_view
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.http import Http404


# Create your views here.
class StudentsList(APIView):
def get(self, request, format=None):
stus = Student.objects.all()
serializer = StudentSerializer(stus, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)

def post(self, request, format=None):
serializer = StudentSerializer(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 StudentDetail(APIView):
def get_object(self, pk):
try:
return Student.objects.get(pk=pk)
except Student.DoesNotExist as e:
raise Http404

def get(self, request, pk, format=None):
stu = self.get_object(pk)
serializer = StudentSerializer(stu)
return Response(serializer.data, status=status.HTTP_200_OK)

def put(self, request, pk, format=None):
stu = self.get_object(pk)
serializer = StudentSerializer(stu, 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)

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

修改路由

1
2
3
4
5
6
7
8
9
10
from django.conf.urls import url
from myApp import views
from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = [

url(r'^students/$', views.StudentsList.as_view()),
url(r'^students/(?P<pk>\d+)', views.StudentDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)

使用Mixins类

  • 基本使用:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    from myApp.models import Student, Grade
    from myApp.serializers import StudentSerializer
    from rest_framework import mixins
    from rest_framework import generics


    # Create your views here.
    # 只有一个父类能继承自APIView
    class StudentsList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
    # 通过get_queryset()和get_serializer()得到集合和序列化
    queryset = Student.objects.all()
    serializer_class = StudentSerializer

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

    def post(self, request, *args, **kwargs):
    return self.create(request, *args, **kwargs)


    class StudentDetail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin,
    generics.GenericAPIView):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer

    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)
  • 使用通用视图:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    from myApp.models import Student, Grade
    from myApp.serializers import StudentSerializer
    from rest_framework import generics


    class StudentsList(generics.ListCreateAPIView):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer


    class StudentDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer