【问题标题】:Where does Django request object originated in `class View`?Django 请求对象起源于 `class View` 的哪里?
【发布时间】:2015-08-19 21:43:39
【问题描述】:

这是我referring to的代码段

@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常用的地方是url

但是我无法在中引用请求对象

def url(regex, view, kwargs=None, name=None, prefix=''):
    if isinstance(view, (list, tuple)):
        # For include(...) processing.
        urlconf_module, app_name, namespace = view
        return RegexURLResolver(regex, urlconf_module, kwargs, app_name=app_name, namespace=namespace)
    else:
        if isinstance(view, six.string_types):
            warnings.warn(
                'Support for string view arguments to url() is deprecated and '
                'will be removed in Django 1.10 (got %s). Pass the callable '
               'instead.' % view,
            RemovedInDjango110Warning, stacklevel=2
            )
            if not view:
                raise ImproperlyConfigured('Empty URL pattern view name not permitted (for pattern %r)' % regex)
            if prefix:
                view = prefix + '.' + view
        return RegexURLPattern(regex, view, kwargs, name)

谁能给我指个方向?

【问题讨论】:

    标签: python django django-views django-urls


    【解决方案1】:

    请注意,请求永远不会传递给as_view()

    as_view() 方法在加载 url 配置时调用,在处理任何请求之前。它定义了一个方法view,并返回它。

    def view(request, *args, **kwargs):
        ...
    return view
    

    这个view 方法接受一个参数request、位置参数和关键字参数。然后将 view 方法传递给 url 实例。请注意,url 只需要一个带有 request 参数的可调用对象。对于基于类的视图或基于常规函数的视图,这可能是通过调用 as_view() 返回的可调用对象,这与将请求传递给视图的方式没有区别。

    def function_view(request, *args, **kwargs):
        return HttpResponse("I'm a function based view")
    
    url(r'^cbv/$', MyView.as_view()),
    url(r'^fv/$', function_view), 
    

    然后,当一个请求被处理时,url被解析成这个viewBaseHandler.get_response用请求调用视图,并从url中捕获args和kwargs。

    【讨论】:

      【解决方案2】:

      请求由BaseHandler.get_response处理:

      wrapped_callback = self.make_view_atomic(callback)
      try:
          response = wrapped_callback(request, *callback_args, **callback_kwargs)
          ...
      

      【讨论】:

        【解决方案3】:

        请求是从WSGIHandler class 创建的。

        James Bennett 在Django In Depth at around 2 hours and 14 minutes 中谈到了这一点。幻灯片可以在here找到。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-11-23
          • 2014-04-19
          • 1970-01-01
          • 2015-02-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多