一、Django的FBV模式和CBV模式
-
Django的视图函数叫FBV(function base view 函数型视图函数)
但是函数是有局限性的,Django中路由一旦匹配成功了,直接导向函数执行了,
即路由映射一个函数 -
在Django中也可以使用类来定义一个视图,称为CBV(Class base view 类视图)。
使用类视图可以将视图对应的不同请求方式以类中的不同方法来区别定义, CBV的本质还是FBV
二、Django的CBV(类视图)源码解析
-
类视图,BookView
-
首先BookView点过去后是没有as_view()方法的,如下图
-
所以as_view()这个方法就往上找,在BookView的父类 View里面
-
装饰器 @classonlymethod 这个方法只能由类对象调用
-
as_view()方法,在Django启动的时候,加载Django的urls.py的时候,在这个py里面就调用了
-
具体看代码解释,写在代码中
class View:
"""
Intentionally simple parent class for all views. Only implements
dispatch-by-method and simple sanity checking.
"""
http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
def __init__(self, **kwargs):
"""
Constructor. Called in the URLconf; can contain helpful extra
keyword arguments, and other things.
"""
# Go through keyword arguments, and either save their values to our
# instance, or raise an error.
for key, value in kwargs.items():
setattr(self, key, value)
@classonlymethod
def as_view(cls, **initkwargs):
"""Main entry point for a request-response process."""
# ========= 解释 ==========
# 检查请求方式 如果没在 规定的方法内(上述类变量http_method_names)就会报错
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError(
'The method name %s is not accepted as a keyword argument '
'to %s().' % (key, cls.__name__)
)
if not hasattr(cls, key):
raise TypeError("%s() received an invalid keyword %r. as_view "
"only accepts arguments that are already "
"attributes of the class." % (cls.__name__, key))
# ========= 解释 ==========
def view(request, *args, **kwargs):
# 进来第一步特别关键,开始做了个实例化
# 这个 cls 是哪个类调用的就是哪个类, views.BookView.as_view(),
# 这块是BookView调用,则这个cls这块就代表的是BookView
# 则 这个 self 就是 BookView 的实例对象
self = cls(**initkwargs)
self.setup(request, *args, **kwargs)
if not hasattr(self, 'request'):
raise AttributeError(
"%s instance has no 'request' attribute. Did you override "
"setup() and forget to call super()?" % cls.__name__
)
# 返回一个函数的执行,这个 self 就是 BookView 的实例对象
# 首先会到 BookView 里面找 dispatch,
# BookView 里面没有,则会到他的父类,里面去找,即View
# dispatch 解释放在下方
return self.dispatch(request, *args, **kwargs)
view.view_class = cls
view.view_initkwargs = initkwargs
# 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=())
# 返回的是个函数,
# path('book/', views.BookView.as_view()), 相当于 返回了这块的view函数 path('book/', View.views)
# 所以本质上相当于还是 FBV模式
# 用户访问book后,比如get请求访问/book/
# get 请求访问/book/ => view() 相当于访问了这个view()函数 => dispatch() => return get()
# post 请求访问/book/ => view() 相当于访问了这个view()函数 => dispatch() => return post()
# 即上述所说的 FBV模式
return view
# ====== 解释(get方法举例) ==========
def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn't on the approved list.
if request.method.lower() in self.http_method_names:
# 反射 找一个方法 request.method.lower() == (get请求就是 "get") 即调用 self.get
# 这个 self 是谁调用的就是谁,即 BookView
# self.get 则先从 BookView 里面找
# BookView就刚好有 get 方法,则就找到了,就会把我们写的get方法执行了
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
# 这块 handler 是self.get 的返回值,
return handler(request, *args, **kwargs)