视图
-
两个视图基类
-
APIView
-
GenericAPIView
-
-
APIView: APIView是REST framework提供的所有视图的基类,继承自Django的View父类
APIView与View的不同之处在于
- 传入到视图方法中的是REST framework的Request对象,而不是Django的HttpRequeset对象
drf进一步封装request对象,更为便捷
- 视图方法可以返回REST framework的Response对象,视图会为响应数据设置(render)符合前端要求的格式
- 任何APIException异常都会被捕获到,并且处理成合适的响应信息
- 在进行dispatch()分发前,会对请求进行身份认证、权限检查、流量控制
- 支持定义的属性
- authentication_classes 列表或元祖,身份认证类
- permissoin_classes 列表或元祖,权限检查类
- throttle_classes 列表或元祖,流量控制类
- get/post等方法,还需要自定义
from rest_framework.views import APIView
from rest_framework.response import Response
# url(r'^books/$', views.BookListView.as_view()),
class BookListView(APIView):
def get(self, request): # get方法要自己写,APIView是没有提供的
books = BookInfo.objects.all()
serializer = BookInfoSerializer(books, many=True)
return Response(serializer.data)
GenericAPIView[通用视图类]
- 继承自APIVIew,主要增加了操作序列化器和数据库查询的方法
作用是为下面Mixin扩展类的执行提供方法支持
通常在使用时,可搭配一个或多个Mixin扩展类
- serializer_class属性 指明视图使用的序列化器,值从以下方法获取
- get_serializer_class(self): 可以返回单个/多个序列化器
def get_serializer_class(self):
# 通过条件判断,返回不同的序列化器
if self.request.user.is_staff:
return FullAccountSerializer
return BasicAccountSerializer
- get_serializer(self, *args, **kwargs): 接收 get_serializer_class()返回值再加点东东
会向序列化器对象的context属性补充三个数据:request、format、view
这三个数据对象可以在定义序列化器时使用
- request 当前视图的请求对象
- view 当前请求的类视图对象
- format 当前请求期望返回的数据格式
def get_serializer(self, *args, **kwargs):
"""
Return the serializer instance that should be used for validating and
deserializing input, and for serializing output.
"""
serializer_class = self.get_serializer_class()
# 加点东东再返回
kwargs.setdefault('context', self.get_serializer_context())
return serializer_class(*args, **kwargs)
-
queryset属性 指明使用的数据查询集
- 值是 get_queryset(self) 的返回值
- 源码默认返回的是所有数据的结果集
......
def get_queryset(self):
# 如果 queryset属性为None,则触发异常
assert self.queryset is not None, (
"'%s' should either include a `queryset` attribute, "
"or override the `get_queryset()` method."
% self.__class__.__name__
)
queryset = self.queryset
if isinstance(queryset, QuerySet):
queryset = queryset.all() # 返回所有的结果集
return queryset
- 可以重写这个方法,返回我们需要的数据集
def get_queryset(self):
user = self.request.user
return user.accounts.all() # 返回用户所有的子账户信息
- get_object(self): 返回详情视图(url需提供pk值,否则报错)所需的模型类数据对象,主要用来提供给Mixin扩展类使用
在视图中可以调用该方法获取详情信息的模型类对象
......
def get_object(self):
queryset = self.filter_queryset(self.get_queryset())
# 找到url路径中传入的pk
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
# 没有传pk值就报错
assert lookup_url_kwarg in self.kwargs, (
'Expected view %s to be called with a URL keyword argument '
'named "%s". Fix your URL conf, or set the `.lookup_field` '
'attribute on the view correctly.' %
(self.__class__.__name__, lookup_url_kwarg)
)
filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
obj = get_object_or_404(queryset, **filter_kwargs)
# 检查该模型对象是否有权限访问
self.check_object_permissions(self.request, obj)
return obj # 最后返回该模型对象
# 举例
# url(r'^books/(?P<pk>\d+)/$', views.BookDetailView.as_view()),
class BookDetailView(GenericAPIView):
queryset = BookInfo.objects.all()
serializer_class = BookInfoSerializer
def get(self, request, pk): # 有传pk
# 模型对象不用再自己手动获取,从get_object()获取即可
book = self.get_object() # get_object()方法根据pk参数查找queryset中的数据对象
serializer = self.get_serializer(book)
return Response(serializer.data)
-
其他可以设置的属性
- pagination_class 指明分页控制类
- filter_backends 指明过滤控制后端
五个视图扩展类
-
作用:
-
提供了几种后端视图(对数据资源进行曾删改查)处理流程的实现
如果需要编写的视图属于这五种,则视图可以通过继承相应的扩展类来复用代码,减少自己编写的代码量 -
这五个扩展类需要搭配GenericAPIView父类
因为五个扩展类的实现需要调用GenericAPIView提供的序列化器与数据库查询的方法
-
-
ListModelMixin:快速实现数据集的展示(若指定分页器,则提供分页功能)
该类没有父类,只有一个list方法
# 源码
class ListModelMixin:
"""
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)
# 举例:继承 ListModelMixin和GenericAPIView,快速实现数据集的展示
from rest_framework.mixins import ListModelMixin
class BookListView(ListModelMixin, GenericAPIView):
queryset = BookInfo.objects.all() # GenericAPIView
serializer_class = BookInfoSerializer # GenericAPIView
def get(self, request):
return self.list(request) # ListModelMixin
- CreateModelMixin: 提供create(request, *args, **kwargs)方法快速实现创建资源的视图,成功返回201状态码
验证失败,则返回400错误
# 源码
'''
- 对数据进行校验
- 校验成功就存入db,返回序列化后的数据(再搭上一个请求头)
- 校验失败就抛异常
'''
class CreateModelMixin:
"""
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 {}
- RetrieveModelMixin: 提供retrieve(request, *args, **kwargs)方法,可以快速实现返回单个模型对象的所有数据
注意:默认需传入pk值,可以通过重写 get_object() 返回该模型对象,从而url不必再传入pk值
# 源码
class RetrieveModelMixin:
"""
Retrieve a model instance.
"""
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
# 没有反序列化,所以不必传data参数,也没有多条数据,所以也不必传many参数
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)
-
UpdateModelMixin: 提供update(request, *args, **kwargs)方法,可以快速实现更新一个存在的数据对象
-
也提供partial_update(request, *args, **kwargs)方法,可以实现局部更新
-
成功返回200,序列化器校验数据失败时,返回400错误
-
class UpdateModelMixin:
"""
Update a model instance.
"""
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False) # 调用update,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):
......
return Response(serializer.data)
def perform_update(self, serializer):
serializer.save()
def partial_update(self, request, *args, **kwargs):
kwargs['partial'] = True # 调用update,partial为True,只更新该条记录的某些字段
return self.update(request, *args, **kwargs)
- DestroyModelMixin: 提供destroy(request, *args, **kwargs)方法,可以快速实现删除一个存在的数据对象
成功返回204,不存在返回404
class DestroyModelMixin(object):
"""
Destroy a model instance.
"""
def destroy(self, request, *args, **kwargs):
instance = self.get_object() # 获取该条记录,然后删除,返回204状态码
self.perform_destroy(instance)
return Response(status=status.HTTP_204_NO_CONTENT)
def perform_destroy(self, instance):
instance.delete()
- 通过上面的视图类学习下来,比如自定义 BookDetailView(RetrieveModelMixin, GenericAPIView)
还需要手动实现get()方法,其他自定义类也如此,所以,可以进一步封装,连get()...等待方法也不用手动再写
有鉴于此,xxxAPIView孕育而生
七个子类视图: xxxAPIView
-
CreateAPIView:
-
继承自: GenericAPIView、CreateModelMixin
-
多写了一个post()方法,返回父类的create()
-
其他子类视图,一模一样的套路
-
# 源码
class CreateAPIView(mixins.CreateModelMixin,
GenericAPIView):
"""
Concrete view for creating a model instance.
"""
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
# 举例: 是的,两行代码就搞定了...
class RegisterView(CreateAPIView):
serializer_class = RegisterSerializer
-
ListAPIView
-
继承自:GenericAPIView、ListModelMixin
-
提供 get(),返回list()
-
# 源码
class ListAPIView(mixins.ListModelMixin,
GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
# 举例:两行代码搞定
class BookMsgView(ListAPIView):
serializer_class = BookSerializer
querset = BookInfo.objects.all()
-
RetrieveAPIView
- 继承自: GenericAPIView、RetrieveModelMixin
- 提供 get 方法
# 源码
class RetrieveAPIView(mixins.RetrieveModelMixin,
GenericAPIView):
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
# 举例
class UserDetailView(RetrieveAPIView):
serializer_class = UserDetailSerialize
def get_object(self):
...... # 是否要传pk值,可以重写这个方法来实现
-
DestoryAPIView
- 继承自:GenericAPIView、DestoryModelMixin
- 提供 delete 方法
# 源码
class DestroyAPIView(mixins.DestroyModelMixin,
GenericAPIView):
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
-
UpdateAPIView
- 继承自:GenericAPIView、UpdateModelMixin
- 提供 put 和 patch 方法
# 源码
class UpdateAPIView(mixins.UpdateModelMixin,
GenericAPIView):
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
return self.partial_update(request, *args, **kwargs)
-
RetrieveUpdateAPIView
- 继承自: GenericAPIView、RetrieveModelMixin、UpdateModelMixin
- 提供 get、put、patch方法
# 源码
class RetrieveUpdateAPIView(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
GenericAPIView):
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 patch(self, request, *args, **kwargs):
return self.partial_update(request, *args, **kwargs)
-
RetrieveUpdateDestoryAPIView
- 继承自:GenericAPIView、RetrieveModelMixin、UpdateModelMixin、DestoryModelMixin
- 提供 get、put、patch、delete方法
# 源码
class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
GenericAPIView):
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 patch(self, request, *args, **kwargs):
return self.partial_update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
标签:get,self,args,request,视图,kwargs,serializer,DRF
From: https://www.cnblogs.com/qinganning/p/16987581.html