您现在的位置是:网站首页> 编程资料编程资料
详解django中视图函数的FBV和CBV_python_
2023-05-26
476人已围观
简介 详解django中视图函数的FBV和CBV_python_
1.什么是FBV和CBV
FBV是指视图函数以普通函数的形式;CBV是指视图函数以类的方式。
2.普通FBV形式
def index(request): return HttpResponse('index')3.CBV形式
3.1 CBV形式的路由
path(r'^login/',views.MyLogin.as_view())
3.2 CBV形式的视图函数
from django.views import View class MyLogin(View): def get(self,request): #get请求时执行的函数 return render(request,'form.html') def post(self,request): #post请求时执行的函数 return HttpResponse('post方法')FBV和CBV各有千秋
CBV特点是:
能够直接根据请求方式的不同直接匹配到对应的方法执行
4.CBV源码分析
核心在于路由层的views.MyLogin.as_view()--->其实调用了as_view()函数就等于调用了CBV里面的view()函数,因为as_view()函数是一个闭包函数,返回的是view---->view函数里面返回了dispatch函数--->dispatch函数会根据请求的方式调用对应的函数!
5.CBV添加装饰器的三种方式
from django.views import View #CBV需要引入的模块 from django.utils.decorators import method_decorator #加装饰器需要引入的模块 """ CBV中django不建议你直接给类的方法加装饰器 无论该装饰器是否能都正常工作 都不建议直接加 """ django给CBV提供了三种方法加装饰器 # @method_decorator(login_auth,name='get') # 方式2(可以添加多个针对不同的方法加不同的装饰器) # @method_decorator(login_auth,name='post') class MyLogin(View): @method_decorator(login_auth) # 方式3:它会直接作用于当前类里面的所有的方法 def dispatch(self, request, *args, **kwargs): return super().dispatch(request,*args,**kwargs) # @method_decorator(login_auth) # 方式1:指名道姓,直接在方法上加login_auth为装饰器名称 def get(self,request): return HttpResponse("get请求") def post(self,request): return HttpResponse('post请求')到此这篇关于django中视图函数的FBV和CBV的文章就介绍到这了,更多相关django视图函数FBV和CBV内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
您可能感兴趣的文章:
相关内容
- pycharm创建并使用虚拟环境的详细图文教程_python_
- conda创建环境、安装包、删除环境步骤详细记录_python_
- python使用pandas读写excel文件的方法实例_python_
- YOLOv5改进之添加SE注意力机制的详细过程_python_
- pyinstaller打包python3.6和PyQt5中各种错误的解决方案汇总_python_
- 使用Pyinstaller打包exe文件详细图文教程_python_
- scrapy框架ItemPipeline的使用_python_
- NumPy 数组属性的具体使用_python_
- python pygame英雄循环飞行及作业示例_python_
- Python pygame 动画游戏循环游戏时钟实现原理_python_
