前言
今天一直在整理Django的rest_framework的序列化组件,前面一共写了2篇博客,前面的博客给的方案都是一个中间的状态的博客,其中有很多的冗余的代码,如果有朋友不清楚,可以先看下我前面的博客
第一篇,使用minix类来实现序列化和反序列化
https://www.cnblogs.com/bainianminguo/p/10463741.html
第二篇,使用通用的类的方法实现序列化和反序列化
https://www.cnblogs.com/bainianminguo/p/10463784.html
这篇我给大家介绍一个终极方案,基于ModelViewSet的序列化和反序列化的方案和源码解析
正文
终极方案之需要一个类就可以分别处理model对象的删改查操作,和queryset对象的增和查操作
先把具体的代码贴上来,让大家有一个整体的概念,然后我一一给大家分析
一、代码
1、首先urls文件
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from app1 import views
app_name = "app1"
urlpatterns = [
url(r'^test/', views.test),
url(r'^test_cbv/', views.test_cbv.as_view(),name="test1"),
url(r'^test_rest/', views.Rest_view.as_view(),name="test2"),
url(r'^book_cbv/', views.Book_cbv.as_view(),name="test3"),
url(r'^publish_detail_cbv/(?P\d+)', views.Pub_detail_cbv.as_view(),name="publish_url_name"),
url(r'^book_detail_cbv/(?P\d+)', views.Book_detail_cbv.as_view(),name="test4"),
# url(r'^autherdetail/(?P\d+)', views.Book_detail_cbv.as_view(), name="autherdetail"),
# url(r'^auther/', views.Book_cbv.as_view(),name="auther"),
url(r'^autherdetail/(?P\d+)/', views.AutherModelCBV.as_view({"get":"retrieve","delete":"destroy","put":"update"}), name="autherdetail"),
url(r'^auther/', views.AutherModelCBV.as_view({"get":"list","post":"create"}),name="auther"),
]
我们用的url是最后两条
我们仔细观察一下,这里的url和之前有3个地方不一样,我一一给大家指出来
a、两个url对应的类是相同的类
b、as_view这个方法有参数,这个参数是一个字典
c、对于model对象的url的url中的变量的名称是pk,之前我们用的id
2、序列化类的代码
class authermodelserializer(serializers.ModelSerializer):
class Meta:
model = models.Auther
fields = "__all__"
序列化的类的代码和之前的保持一致,没有任何改变
3、视图类的代码
from rest_framework import viewsets
class AutherModelCBV(viewsets.ModelViewSet):
queryset = models.Auther.objects.all()
serializer_class = authermodelserializer
我们可以看到这个类非常的简单,这个类继承了一个新的类,我们之前没有用过这个类:viewsets.ModelViewSet
二、流程和源码解析
1、从url的as_view方法开始解读
as_view的源码
@classonlymethod
def as_view(cls, actions=None, **initkwargs):
"""
Because of the way class based views create a closure around the
instantiated view, we need to totally reimplement `.as_view`,
and slightly modify the view function that is created and returned.
"""
# The name and description initkwargs may be explicitly overridden for
# certain route confiugurations. eg, names of extra actions.
cls.name = None
cls.description = None
# The suffix initkwarg is reserved for displaying the viewset type.
# This initkwarg should have no effect if the name is provided.
# eg. 'List' or 'Instance'.
cls.suffix = None
# The detail initkwarg is reserved for introspecting the viewset type.
cls.detail = None
# Setting a basename allows a view to reverse its action urls. This
# value is provided by the router through the initkwargs.
cls.basename = None
# actions must not be empty
if not actions:
raise TypeError("The `actions` argument must be provided when "
"calling `.as_view()` on a ViewSet. For example "
"`.as_view({'get': 'list'})`")
# sanitize keyword arguments
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError("You tried to pass in the %s method name as a "
"keyword argument to %s(). Don't do that."
% (key, cls.__name__))
if not hasattr(cls, key):
raise TypeError("%s() received an invalid keyword %r" % (
cls.__name__, key))
# name and suffix are mutually exclusive
if 'name' in initkwargs and 'suffix' in initkwargs:
raise TypeError("%s() received both `name` and `suffix`, which are "
"mutually exclusive arguments." % (cls.__name__))
def view(request, *args, **kwargs):
self = cls(**initkwargs)
# We also store the mapping of request methods to actions,
# so that we can later set the action attribute.
# eg. `self.action = 'list'` on an incoming GET request.
self.action_map = actions
# Bind methods to actions
# This is the bit that's different to a standard view
for method, action in actions.items():
handler = getattr(self, action)
setattr(self, method, handler)
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
self.request = request
self.args = args
self.kwargs = kwargs
# And continue as usual
return self.dispatch(request, *args, **kwargs)
# take name and docstring from class
update_wrapper(view, cls, updated=())
# and possible attributes set by decorators
# like csrf_exempt from dispatch
update_wrapper(view, cls.dispatch, assigned=())
# We need to set these on the view function, so that breadcrumb
# generation can pick out these bits of information from a
# resolved URL.
view.cls = cls
view.initkwargs = initkwargs
view.actions = actions
return csrf_exempt(view)
函数的代码很长,我们只关注需要我们关注的代码
首先,确定as_view的函数中action的值就是我们的urls中as_view方法中的字典
action的值就是as_view方法中的字典,不信你可以实际测试一下
然后我们看下as_view这个方法的返回值
然后我们在看下as_view中的view方法
def view(request, *args, **kwargs):
self = cls(**initkwargs)
# We also store the mapping of request methods to actions,
# so that we can later set the action attribute.
# eg. `self.action = 'list'` on an incoming GET request.
self.action_map = actions
# Bind methods to actions
# This is the bit that's different to a standard view
for method, action in actions.items():
handler = getattr(self, action)
setattr(self, method, handler)
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
self.request = request
self.args = args
self.kwargs = kwargs
# And continue as usual
return self.dispatch(request, *args, **kwargs)
这里很重要,我们要慢慢来分析
然后在看下view这个方法的返回值
self.request = request
self.args = args
self.kwargs = kwargs
# And continue as usual
return self.dispatch(request, *args, **kwargs)
我们可以看到这个函数的返回值是self.dispatch
我们注意到self.dispatch这个方法,在as_view和view均找不到,这个self是什么呢?这个self就是视图函数的类,所以我们来我们的视图函数的类中找下
明显我们自定义的AuhterModelCBV这个类没有dispatch这个方法,所以我们要去这个类的父类中查找,也就是viewsets.ModelViewSet类中查找
class ModelViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
GenericViewSet):
"""
A viewset that provides default `create()`, `retrieve()`, `update()`,
`partial_update()`, `destroy()` and `list()` actions.
"""
pass
这个类中也没有dispatch方法,但是这个类又继承了6个类,由于继承是从左到右继承,我们从最左边的类开始查找,最终在GeneriViewSet中找到dispatch的方法
class GenericViewSet(ViewSetMixin, generics.GenericAPIView):
"""
The GenericViewSet class does not provide any actions by default,
but does include the base set of generic view behavior, such as
the `get_object` and `get_queryset` methods.
"""
pass
GeneriViewSet的类中也没有dispatch方法,但是这个类有2个父类,所以我们继续往上找
最终在GenericAPIView类中找到了dispatch方法
这个类中也没有dispatch方法,我们在往他的父类中查找
最后,我们终于在APIView类中找到我们需要的dispatch方法
class APIView(View):
def dispatch(self, request, *args, **kwargs):
"""
`.dispatch()` is pretty much the same as Django's regular dispatch,
but with extra hooks for startup, finalize, and exception handling.
"""
self.args = args
self.kwargs = kwargs
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate?
try:
self.initial(request, *args, **kwargs)
# Get the appropriate handler method
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(),
self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
response = handler(request, *args, **kwargs)
except Exception as exc:
response = self.handle_exception(exc)
self.response = self.finalize_response(request, response, *args, **kwargs)
return self.response
下面在看下dispatch方法干了什么
所以执行self.create等方法就会调用我们前面已经对应的self.list。self.update等方法
至此,终极方案我们也完成了!谢谢大家的查阅!