python - Django 请求对象起源于 `class View` 在哪里?

标签 python django django-views django-urls

下面是我的代码段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)

谁能给我指明方向?

最佳答案

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

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

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

view 方法采用参数request、位置参数和关键字参数。 view 方法随后被传递给 url 实例。请注意,url 只需要一个带有 request 参数的可调用对象。这可以是通过为基于类的 View 或基于常规函数的 View 调用 as_view() 返回的可调用对象,它对请求传递到 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 被解析到这个 View BaseHandler.get_response 调用带有请求的 View ,并从中捕获 args 和 kwargs网址。

关于python - Django 请求对象起源于 `class View` 在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32106151/

相关文章:

python - 使用英国日期格式加入 Pandas 数据框

javascript - Django : datepicker in ModelForm

django - 在 Django 中监控 celery 任务

python - 需要帮助加速此功能

python - 标准输出与哈希结果的比较(python)

python - Django 重置密码未捕获无效的电子邮件 ID

django - 创建继承自 APIView 的自定义抽象 View 类

django - 在创建新用户之前检查用户是否存在 djangorestframework

python - 无法使用 gunicorn 主管 django 1.6 使 Newrelic 工作

python - 来自不同 smtp 服务器的电子邮件 django 服务器错误