以下是我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)
有人能指出我的方向吗?
答案 0 :(得分:3)
请注意,请求永远不会传递给as_view()
。
在处理任何请求之前,在加载url配置时调用as_view()
方法。它定义了一个方法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),
然后,当处理请求时,网址会被解析为此view
,BaseHandler.get_response
会根据请求调用视图,并从网址中捕获args和kwargs。
答案 1 :(得分:1)
请求由BaseHandler.get_response
处理:
wrapped_callback = self.make_view_atomic(callback)
try:
response = wrapped_callback(request, *callback_args, **callback_kwargs)
...
答案 2 :(得分:1)
请求是从WSGIHandler class创建的。
James Bennett在Django In Depth at around 2 hours and 14 minutes中谈到了这一点。可以找到幻灯片here。