V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ray1888
V2EX  ›  Django

django 中视图.as_view 函数求详解

  •  
  •   ray1888 ·
    ray1888 · 2017-01-04 17:59:40 +08:00 · 5031 次点击
    这是一个创建于 2907 天前的主题,其中的信息可能已经有所发展或是发生改变。
    看过了 as_view()的源码,还是不是太明白这个函数后面的 update_wrapper 怎样去使得视图运行然后生产 HttpResponse ,有大神懂的话求科普,刚刚上手框架的小白求答案
    ray1888
        1
    ray1888  
    OP
       2017-01-04 18:05:35 +08:00
    在这里贴上源码,方便大神来教导
    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
    honmaple
        2
    honmaple  
       2017-01-04 23:42:29 +08:00
    打个断点,一步一步的看执行的流程,你就明白了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2767 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 21ms · UTC 03:33 · PVG 11:33 · LAX 19:33 · JFK 22:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.