Django中的--View()视图函数--有哪些强大的功能

本文的最后把 View() 的代码在最后展示了,有兴趣的可以瞄一眼。

了解View() 基本的功能,对于我们在后期项目中操作过程中,百利而无一害,haha。

Ⅰ: _ _ init_ _ 实现的功能 - - url中关键字获取

定义了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中调用; 可以包含有用的额外关键字参数和其他内容。

  • 注释其实写的很清楚了,就是如果在请求的url中,有关键字参数,那么这个View()是默认把它保存在类视图的 kwargs属性中的;如果我们向获取这个关键字参数的话,就可以通过这个属性获取;
  • 比如下面这个例子:
    url: sms_codes/(?P<mobile>1[3-9]\d{9}) (通过手机号获取短信验证码),
    类视图:SmsCode(View) (类视图对象:smscode = SmsCode() )
    获取:mobile = smscode.kwargs[“mobile”]

Ⅱ: View()函数 - - 请求的request数据获取

通过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()方法 - - 请求的分发

请求的分发

简单来说,这个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)

Ⅳ:as_view(), view(),dispatch()

在django中,我们一般都会使用类视图,所以在url中,我们会用到as_view(), 那么as_view() 具体实现了什么内容呢?

ps:整个讲解过程,可以附带参考本文最下放的源代码;

比如: url(r'^sms_codes/(?P<mobile>1[3-9]\d{9})/$', views.SmsCode.as_view())

首先,我们是到as_view()这个函数,在as_view()函数中,我们是定义了view() 函数,as_view()函数的返回值是view函数的引用;

其次,我们就会调用view()函数,在进行相关属性的设置之后,view()函数返回的是dispatch函数的引用,所以,我们就顺理成章的来到了dispatch函数

最后,dispatch函数就和之前说的那样,根据不同的请求类型,将返回对应的请求类型以及携带相关的请求参数。


``` class View(object): """ Intentionally simple parent class for all views. Only implements dispatch-by-method and simple sanity checking. """
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)]

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值