gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:54:02 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com