基于类的视图,以及url 路由解析
jumpserver 这个轮子是好跑的轮子,又大又圆,对源码进行解析。
jumpserver 中 用了 大量的基于类的视图函数,相对抽象一点,隐藏了一些细节。大量使用 类似下面的url路由。
urlpatterns = [
url(r'^v1/assets-bulk/$', api.AssetListUpdateApi.as_view(), name='asset-bulk-update')]
跟 基于函数的视图不一样, 配置类视图的时候,需要使用类视图的as_view()方法来注册添加,
as_view 方法 是django 内置base 类中,view类的 类方法。下面贴出源码
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."""
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. as_view "
"only accepts arguments that are already "
"attributes of the class." % (cls.__name__, key))
def view(request, *args, **kwargs):
self = cls(**initkwargs)
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
self.request = request
self.args = args
self.kwargs = kwargs
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=())
return view
as_view 方法返回得是一个函数的引用view, view 方法是 as_view 方法的类方法中的一个内置方法,这个方法 作用是 实例化了一个View类,然后 返回的是实例的dispatch方法。那么dispath 方法 作用是什么呢?下面贴出dispath 方法源码。
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:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)
dispath 先对request 的 method 做了一个判断,返回了handler ,这个handler 是个什么东东?handler 是通过 pythong 内置方法发得到的,下面贴出getattr 方法源码。
def getattr(object, name, default=None): # known special case of getattr
"""
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
"""
getattr 方法发是得到 一个对象 属性或者 方法的引用,django使用这个方法实现了一个反射机制,根据request对象的method 属性,对应 对应试图类的相应方法,如果request 的method 属性 不在 http_method_names 这个列表里面 ,在返回error 视图类。