本文的最后把 View() 的代码在最后展示了,有兴趣的可以瞄一眼。
了解View() 基本的功能,对于我们在后期项目中操作过程中,百利而无一害,haha。
定义了url中的关键字参数是保存在类视图的kwargs属性中,也就是说,在类视图的Kwargs中,可以获取到请求url中的关键字参数。
def __init__(self, **kwargs):
"""
Constructor. Called in the URLconf; can contain helpful extra
keyword arguments, and other things.
"""
# Go through keyword arguments, and either save their values to our
# instance, or raise an error.
for key, value in six.iteritems(kwargs):
setattr(self, key, value)
首先把源代码甩上来,当然了,看不懂代码,可以看注释啊,注释看懂了就知道它的功能了啊;
浏览关键字参数,并将其值保存到实例中,或引发错误。
构造函数。 在URLconf中调用; 可以包含有用的额外关键字参数和其他内容。
sms_codes/(?P1[3-9]\d{9})
(通过手机号获取短信验证码),通过self.request可以获取到请求中的数据
这个功能写的其实比较明显,就是我们在类视图中,可以通过self.request获取本次请求的所有数据;
正如我们所知,一般在视图函数中,能够直接获取到request参数的是那些请求函数(get, put, post…),如果我们需要在类视图中需要定义其他的函数,但是又用到了request的话,我们可以使用self.request直接获取即可。
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)
请求的分发
简单来说,这个dispatch的作用就是请求的分发,根据不同的请求方式,进行访问不同的视图函数,进行不同的操作;
其处理逻辑很简单,就是将获取到的请求方式,和默认列表中的进行比对,如果请求方式存在并且是允许的,,那么就返回相应的请求方式,并携带相应的请求内容handler(request, *args, **kwargs)
;
如果请求不合法或者不在请求列表中,那么将会将这个错误交给http_method_not_allowed
函数,进行处理。
def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn't on the approved list.
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)
在django中,我们一般都会使用类视图,所以在url中,我们会用到as_view(), 那么as_view() 具体实现了什么内容呢?
ps:整个讲解过程,可以附带参考本文最下放的源代码;
比如: url(r'^sms_codes/(?P
首先,我们是到as_view()这个函数,在as_view()函数中,我们是定义了view() 函数,as_view()函数的返回值是view函数的引用;
其次,我们就会调用view()函数,在进行相关属性的设置之后,view()函数返回的是dispatch函数的引用,所以,我们就顺理成章的来到了dispatch函数
最后,dispatch函数就和之前说的那样,根据不同的请求类型,将返回对应的请求类型以及携带相关的请求参数。
http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
def __init__(self, **kwargs):
"""
Constructor. Called in the URLconf; can contain helpful extra
keyword arguments, and other things.
"""
# Go through keyword arguments, and either save their values to our
# instance, or raise an error.
for key, value in six.iteritems(kwargs):
setattr(self, key, value)
@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
def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn't on the approved list.
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)
def http_method_not_allowed(self, request, *args, **kwargs):
logger.warning(
'Method Not Allowed (%s): %s', request.method, request.path,
extra={'status_code': 405, 'request': request}
)
return http.HttpResponseNotAllowed(self._allowed_methods())
def options(self, request, *args, **kwargs):
"""
Handles responding to requests for the OPTIONS HTTP verb.
"""
response = http.HttpResponse()
response['Allow'] = ', '.join(self._allowed_methods())
response['Content-Length'] = '0'
return response
def _allowed_methods(self):
return [m.upper() for m in self.http_method_names if hasattr(self, m)]