zoukankan      html  css  js  c++  java
  • DjangoAgain CBV与FBV

    CBV和FBV

    全称应该是class basic view 和function basic view(不知道后面加不加s)
    理解起来应该就是基于类的视图函数和基于函数的视图函数(那不是就应该加s?)

    实现FBV

    应该是我目前最常用的一种方式了,就是给每一个views里的功能添加自己专用的方法。例如如果要对网页进行get访问,然后通过获得request中post方式传递的form表单获取数据。

        if request.method=="GET":
            return render(request,'login.html')
    
        else:
            input_code=request.POST.get('code')
            session_code=request.session.get('code')
    .....
    

    实现CBV

    但是这种方法,看起来有点臃肿,查看代码的时候不容易看清楚你的post请求get请求是在哪里处理的,所以就有了CBV的处理方法。

    在views文件中:

    def test(request):
        return HttpResponse("...")
    
    from django.views import View
    class login(View):
        def get(self,request):
            return render(request,"login.html")
        def post(self,request):
            ccc=request.POST.get('user')
            print(request.POST.get('user'))
            return HttpResponse(ccc)
    

    上面的test方法是为了做对比。
    在CBV的使用中,需要调用父类View,它会在源码里解释这个CBV的应用范围,以及运作原理。

    在urls文件中:

    from app01 import views
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^test/',views.test),
        url(r'^login.html$',views.login.as_view())
    ]
    

    综上所述:
    我们可以知道设置一个CBV方法,要做的就是,在views里创建一个类,这个类的父类一定得是View,而且在urls设置的时候,url指向的不再是一个函数名,而是你定义的类的.as_view()方法

    运行起来之后,会发现当向login.html这个url发送get请求的时候,成功,发送post请求的时候,也成功,并且有相应的返回值。

    原理

    实现以上功能的核心,其实都在那个被继承的父类View里:

    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)]
    

    扯一下源码来充一充门面。

    从源码中我们可以看到。这个CBV的核心类,是为了处理各种请求服务的。其中有一个list来存放这些请求,并且指向他们应该实现的函数功能。
    再补充一点,在CBV创建类方法的时候,一定要携带一个request参数。而这个参数里面就携带了request.method.lower(),通过反射,CBV函数自然能处理这些method对应的请求。

    看到这里,我就在想,那这个CBV的应用范围不是……很窄吗,直接参考上面的这个allow_list就能知道他能干啥了啊。

    http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
    

    当你定义的处理request方法,不存在这个列表中的时候,按照上面的源码他会报错。但是我不知道怎么模拟……因为这个CBV在urls中定义的方法,并不是一个具体的方法,所以当我在执行这个CBV的时候,他始终存在一个自动匹配的过程。
    当我把原先页面上的form数据传递的method改成一个,不在http_method_names中的test,并且在class里面添加一个test方法(不添加肯定报错啊,想都不要想)。发现这个请求变成了一个get请求,并且自己将form里面的数据修改成了get方式传递。

    [13/Sep/2017 19:17:43] "POST /login.html HTTP/1.1" 200 4
    [13/Sep/2017 19:17:46] "POST /login.html HTTP/1.1" 200 4
    ffff
    [13/Sep/2017 19:17:49] "GET /login.html HTTP/1.1" 200 264
    [13/Sep/2017 19:17:51] "GET /login.html?user=&submit=submit HTTP/1.1" 200 264
    [13/Sep/2017 19:17:54] "GET /login.html?user=sefsefes&submit=submit HTTP/1.1" 200 264
    

    虽然没有试出来这个View在使用别的函数的情况下会有什么样的问题。但是可以发现,既然Django是一个围绕“request”来做开发的web框架,那么大部分操作都应该是围绕着request来做的,所以CBV的确在处理请求的问题上,解决了一部分痛点,并且让代码更加pythonic。

    自定义的dispatch---武基兰的特别操作

    既然在上面我们查看源码的时候已经发现,导向专门的method操作的函数是dispatch,而且每个CBV类的父类都是View,那我能不能在这个dispatch里面做一些定制化操作,让他能够起到一个装饰器的作用(别的修改还是暂时算了吧,比较复杂,得不偿失,不如自己重新写一个FBV)。

    • 继承父类的dispatch
     def dispatch(self, request, *args, **kwargs):
            obj=super(login,self).dispatch(request, *args, **kwargs)
            return obj
            # 由于父类的dispatch最后返回了一个handle,也就是一个返回值,所以在继承的时候也应该提供一个返回值
    
    • 装饰化这个dispatch
        def dispatch(self, request, *args, **kwargs):
            print('request %s is coming...'%request.method)
            obj=super(login,self).dispatch(request, *args, **kwargs)
            print('request is leaving...')
            return obj
    

    反馈的效果:

    [13/Sep/2017 19:57:19] "POST /login.html HTTP/1.1" 200 18
    request POST is coming...
    滴滴滴滴滴滴
    request is leaving...
    request GET is coming...
    [13/Sep/2017 19:57:21] "GET /login.html HTTP/1.1" 200 264
    request is leaving...
    request POST is coming...
    咩哈哈哈哈哈哈
    request is leaving...
    [13/Sep/2017 19:57:26] "POST /login.html HTTP/1.1" 200 21
    

    总的来说,这个只是一个简单的示范处理,如果需要对过来的请求做更多的润色,还需要在这个继承动作前后做更多工作。需要知道的是,他和装饰器略微不懂,那就是他可以共享这个dispatch的request,并且对他进行工作。

  • 相关阅读:
    python 创建文件夹
    Python利用pandas处理Excel数据的应用
    解决git rebase操作后推送远端分支不成功的问题
    LeetCode 1 两数之和
    LeetCode 70 爬楼梯
    LeetCode 11 盛水最多的容器
    LeetCode 283 移动零
    数据结构与算法 ---- 数组 -- Array
    跳表???
    自顶向下编程
  • 原文地址:https://www.cnblogs.com/scott-lv/p/7517475.html
Copyright © 2011-2022 走看看