ray1888
V2EX  ›  Django

django 中视图.as_view 函数求详解

  •  
  •   ray1888 ·
    ray1888 · Jan 4, 2017 · 5716 views
    This topic created in 3611 days ago, the information mentioned may be changed or developed.
    看过了 as_view()的源码,还是不是太明白这个函数后面的 update_wrapper 怎样去使得视图运行然后生产 HttpResponse ,有大神懂的话求科普,刚刚上手框架的小白求答案
    ray1888
    ray1888
    OP
    Jan 4, 2017
    1
    在这里贴上源码,方便大神来教导
    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
    honmaple
    Jan 4, 2017
    2
    打个断点,一步一步的看执行的流程,你就明白了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1226 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 17:40 · PVG 01:40 · LAX 09:40 · JFK 12:40
    ♥ Do have faith in what you're doing.