DRF的视图和路由

1. 视图

Django REST framwork 提供的视图的主要作用:

  • 控制序列化器的执行(检验,保存,转换数据)
  • 控制数据库查询的执行[数据库的删除/查询代码写在视图中,更新和添加写在序列化器]

DRF的视图和路由

1.2 视图

REST framework 提供了众多的通用视图基类与扩展类,以简化视图的编写

1.2.1 两个视图基类

1.2.1.1 APIView

rest_framework.views.APIView

APIView是REST framework提供的所有视图的基类,在继承自Django的View父类

新增以下的内容

新增内容
1.传入到视图方法中的是REST framework的Request对象,而不是Django的HttpRequeset对象;
2.视图方法可以返回REST framework的Response对象,视图会为响应数据设置(renderer)符合前端要求的格式;
3.任何APIException异常都会被捕获到,并且处理成合适的响应信息
4.重写了as_view(),在进行dispatch()路由分发前,会对http请求进行身份认证,权限检查,访问流量控制

支持定义的类属性

类属性名
1.authentication_classes 列表或元组,身份认证类
2.permissoin_classes 列表或元组,权限检查类
3.throttle_classes 列表或元祖,流量控制类

APIView中仍以常规的类视图定义方法来实现get() ,post() 或者其他请求方式的方法.举例:

"""
APIView是drf里面提供的所有视图类的父类,APIView提供的功能/属性/方法是最少的,所以使用APIView基本类似我们使用django的View
GET   /students/ 获取多个学生信息
POST  /students/ 添加一个学生信息
GET    /students/<pk>/  获取一个学生信息 
PUT    /students/<pk>/  修改一个学生信息
DELETE /students/<pk>/  删除一个学生信息
"""
# Create your views here.
from rest_framework.views import APIView
from students.models import Student
from .serializers import StudentModelSerializer
from rest_framework.response import Response
from rest_framework import status

class Student1APIView(APIView):
    def get(self,request):
        """获取所有学生信息"""
        # 1. 获取学生信息的数据模型
        student_list = Student.objects.all()
        # 2. 调用序列化器
        serializer = StudentModelSerializer(instance=student_list, many=True)
        # 3. 返回数据
        return Response(serializer.data)

    def post(self,request):
        """添加一个学生信息"""
        # 1. 调用序列化器对用户提交的数据进行验证
        serializer = StudentModelSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 2. 调用序列化器进行数据库操作
        instance = serializer.save() # save()方法返回的是添加成功以后的模型对象
        serializer = StudentModelSerializer(instance=instance)
        # 3. 返回新增数据
        return Response(serializer.data, status=status.HTTP_201_CREATED)


class Student2APIView(APIView):
    def get(self,request,pk):
        """获取一个学生信息"""
        # 1. 根据pk获取模型对象
        student = Student.objects.get(pk=pk)
        # 2. 序列化器转换数据
        serializer = StudentModelSerializer(instance=student)
        # 3. 响应数据
        return Response(serializer.data)

    def put(self,request,pk):
        """修改一个学生信息"""
        # 1. 通过pk查询学生信息
        student = Student.objects.get(pk=pk)
        # 3. 调用序列化器对客户端发送过来的数据进行验证
        serializer = StudentModelSerializer(instance=student, data=request.data)
        serializer.is_valid(raise_exception=True)
        # 4. 保存数据
        instance = serializer.save() #?这里实际上调用的序列化器里面的update方法
        serializer = StudentModelSerializer(instance=instance)
        # 5. 返回结果
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def delete(self, request, pk):
        # 1. 通过pk查询学生信息
        Student.objects.get(pk=pk).delete()
        return Response({"message":"ok"}, status=status.HTTP_204_NO_CONTENT)

1.2.1.2 GenericAPIView

GenericAPIView视图类继承自APIView,主要增加了操作序列化器数据库查询的方法,作用是为下面Mixin扩展类的执行提供方法支持.

rest_framework.generics.GenericAPIView

属性

属性名 含义
serializer_class 指明视图使用的序列化器
queryset 指明使用的数据查询集
pagination_class 指明分页控制类
filter_backends 指明过滤控制后端

方法

方法名 含义
get_serializer_class(self) 重写此方法可以满足同一个视图类中需要调用多个序列器的要求
**get_serializer(self, args, *kwargs) 返回序列化器对象,
注意:该方法在提供序列化器对象的时候,会向序列化器对象的context属性补充三个数据:request、format、view,这三个数据对象可以在定义序列化器时使用
request 当前视图的请求对象
view 当前请求的类视图对象
format 当前请求期望返回的数据格式
get_queryset(self) 返回视图使用的查询集
get_object(self) 返回单个视图模型类对象
该方法会默认使用APIView提供的check_object_permissions方法检查当前对象是否有权限被访问

视图类

from rest_framework.generics import GenericAPIView
from students.models import Student
from .serializers import StudentModelSerializer, StudentModel2Serializer
from rest_framework.response import Response

class StudentsGenericAPIView(GenericAPIView):
    # 本次视图类中要操作的数据[必填]
    queryset = Student.objects.all()
    # 本次视图类中要调用的默认序列化器[选填]
    serializer_class = StudentModelSerializer

    def get(self, request):
        """获取所有学生信息self.queryset().all()"""
        serializer = self.get_serializer(instance=self.get_queryset(), many=True)
        return Response(serializer.data)

    def post(self,request):
        data = request.data
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        instance = serializer.save()
        serializer = self.get_serializer(instance=instance)
        return Response(serializer.data)


class StudentGenericAPIView(GenericAPIView):
    queryset = Student.objects.all()
    serializer_class = StudentModelSerializer

    def get_serializer_class(self):
        """重写获取序列化器类的方法"""
        if self.request.method == "GET":
            return StudentModel2Serializer
        else:
            return StudentModelSerializer

    # 在使用GenericAPIView视图获取或操作单个数据时,视图方法中的代表主键的参数最好是pk
    def get(self,request,pk):
        """获取一条数据"""
        serializer = self.get_serializer(instance=self.get_object())
        return Response(serializer.data)

    def put(self,request,pk):

        data = request.data
        serializer = self.get_serializer(instance=self.get_object(),data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        serializer = self.get_serializer(instance=self.get_object())
        return Response(serializer.data)

序列化器类:

class StudentModel2Serializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ("id", "name", "sex", "age", "class_num")
        read_only_fields = ('id',)
        extra_kwargs = {
            "id": { "required": True},
            "name": {"required": True},
            "age": {"max_value": 60, "required": True}
        }


class StudentModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = "__all__"

1.2.2 5个视图扩展类

作用:提升代码复用度,实现对数据资源的增删改查

注意:这五个扩展类需要搭配GenericAPIView父类,因为需要用到GenericAPIView提供的序列化器与数据库查询的方法。

视图类名 含义 提供的方法
ListModelMixin 获取多条数据 list()
RetrieveModelMixin 获取一条数据 retrieve()
CreateModelMixin 添加一条数据 create()
UpdateModelMixin 更新一条数据 update()
DestroyModelMixin 删除一套数据 destroy()

1.ListModelMixin

列表视图扩展类,提供list(request, *args, **kwargs)方法快速实现列表视图,返回200状态码.该Mixin的list方法会对数据进行过滤和分页

源代码:

class ListModelMixin(object):
    """
    List a queryset.
    """
    def list(self, request, *args, **kwargs):
        # 过滤
        queryset = self.filter_queryset(self.get_queryset())
        # 分页
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        # 序列化
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

举例:

from rest_framework.mixins import ListModelMixin
class BookListView(ListModelMixin, GenericAPIView):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer
    def get(self, request):
        return self.list(request)

2.CreateModelMixin

创建视图扩展类,提供create(request, *args, **kwargs)方法快速实现创建资源的视图,成功返回201状态码。

如果序列化器对前端发送的数据验证失败,返回400错误

源代码:

class CreateModelMixin(object):
    """Create a model instance"""
    def create(self, request, *args, **kwargs):
        # 获取序列化器
        serializer = self.get_serializer(data=request.data)
        # 验证
        serializer.is_valid(raise_exception=True)
        # 保存
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        serializer.save()

    def get_success_headers(self, data):
        try:
            return {'Location': str(data[api_settings.URL_FIELD_NAME])}
        except (TypeError, KeyError):
            return {}

3.RetrieveModelMixin

详情视图扩展类提供retrieve(request, *args, **kwargs)方法,可以快速实现返回一个存在的数据对象。

如果存在,返回200,否则返回404。

源代码:

class RetrieveModelMixin(object):
    """
    Retrieve a model instance.
    """
    def retrieve(self, request, *args, **kwargs):
        # 获取对象,会检查对象的权限
        instance = self.get_object()
        # 序列化
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

举例:

class BookDetailView(RetrieveModelMixin, GenericAPIView):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer

    def get(self, request, pk):
        return self.retrieve(request)

4.UpdateModelMixin

更新视图扩展类,提供update(request, *args, **kwargs)方法,可以快速实现更新一个存在的数据对象。

同时也提供partial_update(request, *args, **kwargs)方法,可以实现局部更新.成功返回200,序列化器校验数据失败时,返回400错误。

源代码:

class UpdateModelMixin(object):
    """Update a model instance."""
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}
        return Response(serializer.data)

    def perform_update(self, serializer):
        serializer.save()

    def partial_update(self, request, *args, **kwargs):
        kwargs['partial'] = True
        return self.update(request, *args, **kwargs)

5.DestroyModelMixin

删除视图扩展类,提供destroy(request, *args, **kwargs)方法,可以快速实现删除一个存在的数据对象.成功返回204,不存在返回404。

源代码:

class DestroyModelMixin(object):
    """Destroy a model instance."""
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response(status=status.HTTP_204_NO_CONTENT)

    def perform_destroy(self, instance):
        instance.delete()

使用GenericAPIView和视图扩展类,实现api接口,代码:

"""GenericAPIView结合视图扩展类实现api接口"""
from rest_framework.mixins import ListModelMixin,CreateModelMixin
class Students2GenericAPIView(GenericAPIView,ListModelMixin,Creat eModelMixin):
    # 本次视图类中要操作的数据[必填]
    queryset = Student.objects.all()
    # 本次视图类中要调用的默认序列化器[选填]
    serializer_class = StudentModelSerializer

    def get(self, request):
        """获取多个学生信息"""
        return self.list(request)

    def post(self,request):
        """添加学生信息"""
        return self.create(request)


from rest_framework.mixins import RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin
class Student2GenericAPIView(GenericAPIView,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin):
    queryset = Student.objects.all()

    serializer_class = StudentModelSerializer

    # 在使用GenericAPIView视图获取或操作单个数据时,视图方法中的代表主键的参数最好是pk
    def get(self,request,pk):
        """获取一条数据"""
        return self.retrieve(request,pk)

    def put(self,request,pk):
        """更新一条数据"""
        return self.update(request,pk)

    def delete(self,request,pk):
        """删除一条数据"""
        return self.destroy(request,pk)

1.2.3 GenericAPIView的视图子类

视图子类名 继承自 方法
CreateAPIView GenericAPIView、CreateModelMixin 提供 post 方法
RetrieveAPIView GenericAPIView、RetrieveModelMixin 提供 get 方法
DestoryAPIView GenericAPIView、DestoryModelMixin 提供 delete 方法
UpdateAPIView GenericAPIView、UpdateModelMixin 提供 put 和 patch 方法
RetrieveUpdateAPIView GenericAPIView、RetrieveModelMixin、UpdateModelMixin 提供 get、put、patch方法
RetrieveUpdateDestoryAPIView GenericAPIView、RetrieveModelMixin、UpdateModelMixin、DestoryModelMixin 提供 get、put、patch、delete方法

1.3 视图集ViewSet

为了让视图代码变得更加简短,让操作同一个模型的视图方法写在一个视图类中, drf提供了视图集[viewsets],

1.视图集允许开发者自定义类视图方法名

2.视图集允许一个类分配多个不同的路由

使用视图集ViewSet,可以将一系列逻辑相关的动作放到一个类中

相关动作 含义
list(),retrieve(),create(),update(),destory() 提供一组数据
retrieve() 提供单个数据
create() 创建数据
update() 保存数据
destory() 删除数据

注意

ViewSet视图集类不再实现get(),post()等方法,而是实现动作 action 如 list() ,create() 等

视图集只在使用as_view()方法的时候,才会将action动作与具体请求方式对应上

1.3.1 常用视图集父类

视图集名 特点
ViewSet 1.继承自APIViewViewSetMixin
2.APIView提供了身份认证,权限校验,流量管理等
3.ViewSetMixin通过调用as_view()时传入字典(如{‘get’:‘list’})的映射处理工作
4.ViewSet中,没有提供任何动作action方法,需要我们自己实现action方法
GenericViewSet 1.继承自GenericAPIViewViewSetMixin
2.搭配GenericViewSet,ListModelMixin,CreateModelMixin,RetrieveModelMixin,
UpdateModelMixin,DestroyModelMixin使用实现,list,retrieve,create,update,destory 等方法
3.通过继承ViewSetMixin来实现在调用as_view()时传入字典,(如{'get':'list'}
ModelViewSet 1.继承自GenericViewSet
2.同时包括了ListModelMixin,RetrieveModelMixin,CreateModelMixin、UpdateModelMixin、DestoryModelMixin。
ReadOnlyModelViewSet 1.继承自GenericViewSet,同时包括了ListModelMixin,RetrieveModelMixin。

1 ViewSet

views.py

class Student7APIViewSet(ViewSet):
    def list(self,request):
        """获取多条数据"""
        student_list = Student.objects.all()
        serializer = StudentModelSerializer(instance=student_list,many=True)
        return Response(serializer.data)

    def get(self,request,pk):
        """获取一条数据"""
        student = Student.objects.get(pk=pk)
        serializer = StudentModelSerializer(instance=student)
        return Response(serializer.data)

urls.py

urlpatterns = [
    path("students7/", views.Student7APIViewSet.as_view({"get":"list"})),
    re_path("^students7/(?P<pk>\d+)/$", views.Student7APIViewSet.as_view({"get":"get"}))
]

2.GenericViewSet

views.py

from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin,CreateModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin
class Student8ViewSet(GenericViewSet,ListModelMixin,CreateModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin):
    queryset = Student.objects.all()
    serializer_class = StudentModelSerializer

urls.py

urlpatterns = [
    path("students8/", views.Student8ViewSet.as_view({"get": "list", "post": "create"})),
    re_path("students8/(?P<pk>\d+)/", views.Student8ViewSet.as_view({"get": "retrieve","put":"update","delete":"destroy"})),

]

3.ModelViewSet

views.py

from rest_framework.viewsets import ModelViewSet
class Student9ViewSet(ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentModelSerializer

urls.py

urlpatterns = [
    path("students9/", views.Student8ViewSet.as_view({"get": "list", "post": "create"})),
    re_path("students9/(?P<pk>\d+)/", views.Student8ViewSet.as_view({"get": "retrieve","put":"update","delete":"destroy"})),

]

4.ReadOnlyModelViewSet

views.py

from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin,CreateModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin
class Student8ViewSet(GenericViewSet,ListModelMixin):
    queryset = Student.objects.all()
    serializer_class = StudentModelSerializer
    def get_serializer_class(self):
        print(self.action) # 本次请求的视图方法名称
        if self.action.lower() == "list":
            return Student2ModelSerializer
        else:
            return StudentModelSerializer

urls.py

urlpatterns = [
    path("students8/", views.Student8ViewSet.as_view({"get": "list", "post": "create"})),
    re_path("students8/(?P<pk>\d+)/", views.Student8ViewSet.as_view({"get": "retrieve","put":"update","delete":"destroy"})),
]

1.3.2 定义action动作

手动指明请求方式与动作action之间的对应关系

from rest_framework.viewsets import ModelViewSet,ReadOnlyModelViewSet
class StudentModelViewSet(ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentModelSerializer

    def login(self,request):
        """学生登录功能"""
        return Response({"message":"登录成功"})

url的定义

urlpatterns = [
    path("students8/", views.StudentModelViewSet.as_view({"get": "list", "post": "create"})),
    re_path("students8/(?P<pk>\d+)/",
            views.StudentModelViewSet.as_view({"get": "retrieve", "put": "update", "delete": "destroy"})),

    path("stu/login/",views.StudentModelViewSet.as_view({"get":"login"}))

]

1.3.3 action属性

通过action对象属性获取当前请求视图集时的action动作

views.py

from rest_framework.viewsets import ModelViewSet
from students.models import Student
from .serializers import StudentModelSerializer
from rest_framework.response import Response
class StudentModelViewSet(ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentModelSerializer
    def get_new_5(self,request):
        """获取最近添加的5个学生信息"""
        # 获取本次请求的视图方法名get_new_5    
        print(self.action)      

url.py

urlpatterns = [
    path("get_new_5",views.StudentModelViewSet.as_view({"get":"get_new_5"}))
]

2. 路由Routers

对于视图集ViewSet,我们除了可以自己外,还可以使用Routers来帮助我们快速实现路由信息。

REST framework提供了两个router

  • SimpleRouter(错误时直接报错)
  • DefaultRouter(错误时提示api的根目录)

2.1 基本使用

目地:

给特定的方法诸如(list(),retrieve(),create(),update(),destory())等自动生成路由

1.创建router对象,并注册视图集

from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'student9', StudentModelViewSet, base_name='student')
print(router.urls)
#^student9/$    name: student-list, ^student9/{pk}/$   name: student-detail

register(prefix, viewset, base_name)

参数名 含义
prefix 该视图集的路由前缀
viewset 视图集
base_name 路由别名的前缀

2 添加路由数据两种方式

方式一:

urlpatterns = [
    ...
]
urlpatterns += router.urls

方式二:

urlpatterns = [
    ...
    url(r'^', include(router.urls))
]

views.py

from rest_framework.viewsets import ModelViewSet,ReadOnlyModelViewSet
class StudentModelViewSet(ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentModelSerializer

    def login(self,request):
        """学生登录功能"""
        print(self.action)
        return Response({"message":"登录成功"})

urls.py

from django.urls import path, re_path
from . import views
urlpatterns = [
    ...
]
# 实例化路由类
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
# 注册视图集
router.register("router_stu",views.StudentModelViewSet)
# 把生成的路由列表追加到urlpatterns
print( router.urls )
urlpatterns += router.urls

2.2 action声明

目的:

在自定义方法上使用action装饰器,让Router给自定义方法生成路由

from rest_framework.decorators import action

action装饰器可以接收两个参数:

参数名
methods 声明该action对应的请求方式,列表传递
detail 声明该action的路径是否与单一资源对应否是操作一个数据
url_path 设置访问当前方法的子路由,如果不配置,则默认是是当前方法名

注意:

detail中的True 表示路径格式是xxx/<pk>/action方法名/,False 表示路径格式是xxx/action方法名/

举例:

from rest_framework.decorators import action

class StudentModelViewSet(ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentModelSerializer

    # detail为True,表示路径名格式应该为 router_stu/{pk}/login/
    @action(methods=['get'], detail=True)
    def login(self, request,pk):
        return Response("测试数据login")
        

    # detail为False 表示路径名格式应该为 router_stu/get_new_5/
    @action(methods=['put'], detail=False)
    def get_new_5(self, request):
        """获取最新添加的5个学生信息"""
        return Response("测试数据get_new_5")

由路由器自动为此视图集自定义action方法形成的路由会是如下内容:

^router_stu/get_new_5/$    name: router_stu-get_new_5
^router_stu/{pk}/login/$   name: router_stu-login

2.3 router形成URL的方式

1) SimpleRouter

DRF的视图和路由

2)DefaultRouter

DRF的视图和路由

DefaultRouter与SimpleRouter的区别

DefaultRouter会多附带一个默认的API根视图,返回一个包含所有列表视图的超链接响应数据

上一篇:drf-序列化器serializer


下一篇:序列化器-Serializer