美文网首页
django的cbv

django的cbv

作者: Elvis_zhou | 来源:发表于2018-07-13 11:29 被阅读0次

FBV

FBV(function base views) 就是在视图里使用函数处理请求。

在之前django的学习中,我们一直使用的是这种方式,所以不再赘述。

CBV

CBV(class base views) 就是在视图里使用类处理请求。

Python是一个面向对象的编程语言,如果只用函数来开发,有很多面向对象的优点就错失了(继承、封装、多态)。所以Django在后来加入了Class-Based-View。可以让我们用类写View。这样做的优点主要下面两种:

  1. 提高了代码的复用性,可以使用面向对象的技术,比如Mixin(多继承)
  2. 可以用不同的函数针对不同的HTTP方法处理,而不是通过很多if判断,提高代码可读性

CBV.as_view()

在Django的路由中为url指定view的时候,如果为类视图(所有类视图都需要继承于基类View),则需要使用as_view方法将类视图转化为一个函数,接下来笔者就分析一下as_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)

    # as_view方法经过类方法装饰器,是一个类方法
    @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())

其实as_view方法在方法中定义了一个view函数,这个函数接受的参数跟FBV接受的参数一样,但是这个函数并不负责根据http的method分配到具体的CBV的method上,而是将这项工作交给了dispatch方法去完成。最后as_view方法返回了这个view函数。

在dispatch方法中,寻找了开发者自行定义的诸如get,post等方法对应的业务逻辑并返回执行结果,如果开发者没有定义该方法,则返回405表示该方法不允许。

相关文章

  • Django基础:drf 源码视图解析

    Django 与drf 源码视图解析 一.原生Django CBV 源码分析:View 二.drf CBV 源码分...

  • Django中的CBV

    django中请求处理方式有2种:FBV 和 CBV CBV CBV(class base views) 就是在视...

  • DRF进阶

    一、Django的FBV和CBV FBV:Function-base views基于函数的视图CBV:Class-...

  • Django 的 cbv

    正如我们了解到的,Django 写视图函数有两种写法:cbv 和 fbv。cbv 提倡使用类来写,fbv 使用函数...

  • django的cbv

    FBV FBV(function base views) 就是在视图里使用函数处理请求。 在之前django的学习...

  • Django使用CBV处理请求

    在Django中有两种基本的处理用户请求的方式,分别是FBV和CBV,这里讲的是关于使用CBV处理用户请求的方式 ...

  • Django之CBV

    CBV,即Class Base View,类基本视图。在写API时,我们通常都是使用CBV,而非FBV (Func...

  • Django中CBV

    一.django处理业务逻辑的两种方式 FBV (function based views):使用函数来处理业务逻...

  • 第三天

    drf开发商品列表页 django的view实现商品列表页&自带的serializer cbv => class ...

  • Django-FBV 和 CBV

    FBV 和 CBV django中请求处理方式有2种: FBV(function base views)** 就是...

网友评论

      本文标题:django的cbv

      本文链接:https://www.haomeiwen.com/subject/bwcouftx.html