2023年6月25日发(作者:)
基于django开发的框架jumpserver源码解析(⼀)基于类的视图,以及url路由解析基于类的视图,以及url 路由解析 jumpserver 这个轮⼦是好跑的轮⼦,⼜⼤⼜圆,对源码进⾏解析。
jumpserver 中 ⽤了 ⼤量的基于类的视图函数,相对抽象⼀点,隐藏了⼀些细节。⼤量使⽤ 类似下⾯的url路由。urlpatterns = [ url(r'^v1/assets-bulk/$', _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 (): 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 _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'): = t = request = args = kwargs return ch(request, *args, **kwargs) _class = cls _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, ch, assigned=()) return viewas_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 () in _method_names: handler = getattr(self, (), _method_not_allowed) else: handler = _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 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 视图类。
发布者:admin,转转请注明出处:http://www.yc00.com/web/1687678263a30831.html
评论列表(0条)