CBV源码分析

FBV和CBV

FBV(function base views) : 在视图层中使用函数处理请求

CBV(class base views): 在视图层中使用类处理请求

Python是一个面向对象的编程语言, 面向对象的优点(继承,封装,多态), 使用CBV,用类写view,这样的做的优点:

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

CBV简单示例

# 在urls.py中进行路由配置
urlpatterns = [
    # (正则表达式,  函数内存地址)
    url(r'^admin/', admin.site.urls),
    url(r'^books/$', views.Books.as_view()),
]
# views视图中
from django.views import  View
class Books(View):
    def get(self,request, *args, **kwargs):
        print("get")
        return HttpResponse("ok")

    def dispatch(self, request, *args, **kwargs):
        print("dispatch")
        ret = super(Books,self).dispatch(request, *args, **kwargs)
        print("ret",ret)
        return  HttpResponse(ret)

'''
输出结果为:
dispatch
get
ret <HttpResponse status_code=200, "text/html; charset=utf-8">
'''

源码分析

# 从views.Books.as_view()入手, 先了解as_view方法

class View(object):
    http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

    def __init__(self, **kwargs):
        "省略"

    @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

由于配置的views.IndexView.as_view()参数为null,所以在for key in initkwargs会直接跳过,如果不为null,就去判断执行接下来的代码,大概意思就是,if key in cls.http_method_names:if not hasattr(cls, key):,如果传递过来的字典中某键包含在 http_method_names列表中列表中和本类中没有该键属性都会跑出异常

http_method_nameshttp_method_names = [‘get‘, ‘post‘, ‘put‘, ‘patch‘, ‘delete‘, ‘head‘, ‘options‘, ‘trace‘]

as_view函数下内置一个方法def view(request, *args, **kwargs):


  # 函数可以当做对象来使用, 一切皆对象
  # 为view函数添加了属性
            view.view_class = cls
        view.view_initkwargs = initkwargs

  # 再次对view函数添加属性
        # 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=())
# 点进 update_wrapper

WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__qualname__', '__doc__',
                       '__annotations__')
WRAPPER_UPDATES = ('__dict__',)
def update_wrapper(wrapper,
                   wrapped,
                   assigned = WRAPPER_ASSIGNMENTS,
                   updated = WRAPPER_UPDATES):
    """Update a wrapper function to look like the wrapped function

       wrapper is the function to be updated
       wrapped is the original function
       assigned is a tuple naming the attributes assigned directly
       from the wrapped function to the wrapper function (defaults to
       functools.WRAPPER_ASSIGNMENTS)
       updated is a tuple naming the attributes of the wrapper that
       are updated with the corresponding attribute from the wrapped
       function (defaults to functools.WRAPPER_UPDATES)
    """
    for attr in assigned:
        try:
            value = getattr(wrapped, attr)
        except AttributeError:
            pass
        else:
            setattr(wrapper, attr, value)
    for attr in updated:
        getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
    # Issue #17482: set __wrapped__ last so we don't inadvertently copy it
    # from the wrapped function when updating __dict__
    wrapper.__wrapped__ = wrapped
    # Return the wrapper so this can be used as a decorator via partial()
    return wrapper

为view函数添加了一些属性,用来更新某些操作,以及可以获取某些数据操作,比如WRAPPER_UPDATES = (‘__dict__‘,)

# view函数

            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

为本类实例对象赋值request、args、kwargs,最后执行return self.dispatch(request, *args, **kwargs) (相当于一个装饰器的功能, 可以自定义内容) , 所以views.Books.as_view()中的url配置最后会返回view方法

view方法体再次对本类对象进行了一些封装,也是面向对象最主要的特征.比如:self.request = request, self.args = args, self.kwargs = kwargs

# dispatch函数

    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)

通过判断request的请求方式,通过反射的方式,判断是否在http_method_names列表中,没有的话进行相关处理,赋值操作handlerhandler = self.http_method_not_allowed

如果没有找到, 就会构造一个默认的

    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())
class HttpResponseNotAllowed(HttpResponse):
    status_code = 405

    def __init__(self, permitted_methods, *args, **kwargs):
        super(HttpResponseNotAllowed, self).__init__(*args, **kwargs)
        self['Allow'] = ', '.join(permitted_methods)

    def __repr__(self):
        return '<%(cls)s [%(methods)s] status_code=%(status_code)d%(content_type)s>' % {
            'cls': self.__class__.__name__,
            'status_code': self.status_code,
            'content_type': self._content_type_for_repr,
            'methods': self['Allow'],
        }

handler(request, *args, **kwargs),其实就是执行代码中CBVBooksget方法

原文地址:https://www.cnblogs.com/kp1995/p/10596248.html

时间: 2024-07-31 02:57:18

CBV源码分析的相关文章

Django框架 --CBV源码分析、restful规范、restframework框架

一.CBV源码分析 1.url层的使用CBV from app01 import views url(r'book/',views.Book.as_view()) 2.as_view方法 as_view是一个类方法,实际上是一个闭包函数(内层函数包含对外层作用域的使用) 请求来了以后,调用as_view方法,调用函数中的view方法,view方法是调用了dispatch方法 @classonlymethod def as_view(cls, **initkwargs): def view(req

FBV与CBV 及CBV源码分析

FBV与CBV 及CBV源码分析 FBV(Function Based View) 基于函数的视图 基于函数的视图,我们一直在用没啥好讲的,就是导入模块调用函数执行业务 CBV(Class Based View) 基于类的视图 路由 from app01 import views url(r'^haha/',views.zx_view.as_view()), 视图 class zx_view(View): def get(self,request): return render(request,

django中CBV源码分析

前言:Django的视图处理方式有两种: FBV(function base views) 是在视图里基于函数形式处理请求. CBV(class base views)是在视图里基于类的形式处理请求. Python是一个面向对象的编程语言,如果只用函数来开发,有很多面向对象的优点就错失了(继承.封装.多态).所以Django在后来加入了Class-Based-View.可以让我们用类写View.这样做的优点主要下面两种: 提高了代码的复用性,可以使用面向对象的技术,比如Mixin(多继承) 可以

django中cbv源码和restful规范

1 django 请求声明周期 -先进入实现了wsgi协议的web服务器---->进入django--->中间件--->路由--->视图--->取模板,取数据,用数据渲染模板--->返回模板的字符串--->在浏览器上看到页面了 2 开发模式(前后端分离和前后端不分离) -前后端不分离项目 -前后端分离项目 前端和后端通过json格式数据交互 3 cbv 源码分析 -FBV和CBV -执行流程: -路由如果这么配置:url(r'^test/', views.Test

Django中CBV和Restful API中的APIView源码分析

Django中CBV和Restful API中的APIView源码分析 python的Django框架的视图处理可以用FBV, 也可以采用CBV.首先定义一个CBV视图: from django.views import Viewfrom django.http import JsonResponseclass Book(View):    def get(self, request):        ll = [{'key':value}]        return JsonResponse

Django rest framework源码分析(一) 认证

一.基础 最近正好有机会去写一些可视化的东西,就想着前后端分离,想使用django rest framework写一些,顺便复习一下django rest framework的知识,只是顺便哦,好吧.我承认我是故意的,因为我始终觉得,如果好的技术服务于企业,顺便的提高一下自己.大家都很开心不是不.再次强调一下,真的只是顺便. 安装吧 pip install djangorestframework 1.2.需要先了解的一些知识 理解下面两个知识点非常重要,django-rest-framework

Django-jwt token生成源码分析

一. 认证的发展历程简介 这里真的很简单的提一下认证的发展历程.以前大都是采用cookie.session的形式来进行客户端的认证,带来的结果就是在数据库上大量存储session导致数据库压力增大,大致流程如下: 在该场景下,分布式.集群.缓存数据库应运而生,认证的过程大致如下: 不过该方式还是缓解不了数据库压力,一个项目中应该尽可能多的减少IO操作,于是后来采用签名的方式,在服务端只保存token的签名算法,当客户端认证时,只需用算法去生成或是判断token的合法性即可.大致方式如下: 二.

django-rest framework 接口规范 原生django接口、单查群查 postman工具 CBV源码解析

内容了解 """ 1.接口:什么是接口.restful接口规范 2.CBV生命周期源码 - 基于restful规范下的CBV接口 3.请求组件.解析组件.响应组件 4.序列化组件(灵魂) 5.三大认证(重中之重):认证.权限(权限六表).频率 6.其他组件:过滤.筛选.排序.分页.路由 """ # 难点:源码分析 一.接口 1.什么是 接口:联系两个物质的媒介,完成信息交互 web程序中:联系前台页面与后台数据库的媒介 web接口组成: url:

TeamTalk源码分析之login_server

login_server是TeamTalk的登录服务器,负责分配一个负载较小的MsgServer给客户端使用,按照新版TeamTalk完整部署教程来配置的话,login_server的服务端口就是8080,客户端登录服务器地址配置如下(这里是win版本客户端): 1.login_server启动流程 login_server的启动是从login_server.cpp中的main函数开始的,login_server.cpp所在工程路径为server\src\login_server.下表是logi