前言
本文主要给大家介绍了关于Django中CBV和FBV的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。
一、 CBV
CBV是采用面向对象的方法写视图文件。
CBV的执行流程:
浏览器向服务器端发送请求,服务器端的urls.py根据请求匹配url,找到要执行的视图类,执行dispatch方法区分出是POST请求还是GET请求,执行views.py对应类中的POST方法或GET方法。
使用实例:
urls.py
path('login/',views.Login.as_view())views.py
from django import views #在views.py的基础上添加
class Login(views.Views):
 def get(self,request)
 pass
 def pass(self,request)
 pass使用装饰器:
from django import views
from django.utils.decorators import method_decorator
def outer(func):
 def inner(request,*args,**kwargs):
 return func(request,*args,**kwargs)
 return inner
class Login(views.View):
 @method_decorator(outer)
 def get(self,request,*args,**kwargs):
 pass在类上面加装饰器,和在函数上加装饰器是一个性质。但加的方法有所不同。
eg:
@method_decorator(outer,name='dispatch')
class Login(views.View):自定义dispatch:
class Login(views.View):
 def dispatch(self, request, *args, **kwargs):
 print(2222)
 ret = super(Login, self).dispatch(request, *args, **kwargs)
 print(1111)
 return ret
def get(self, request, *args, **kwargs):
 print('GET')
 return HttpResponse('OK')执行结果:2222
 GET
 1111二、 FBV
FBV即在views.py中以函数的形式写视图。
看代码:
urls.py
from django.conf.urls import url, include
# from django.contrib import admin
from mytest import views
 
urlpatterns = [
 # url(r‘^admin/‘, admin.site.urls),
 url(r‘^index/‘, views.index),
]views.py
from django.shortcuts import render
def index(req):
 if req.method == ‘POST‘:
 print(‘method is :‘ + req.method)
 elif req.method == ‘GET‘:
 print(‘method is :‘ + req.method)
 return render(req, ‘index.html‘)注意此处定义的是函数【def index(req):】
index.html
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>index</title>
</head>
<body>
 <form action="" method="post">
 <input type="text" name="A" />
 <input type="submit" name="b" value="提交" />
 </form>
</body>
</html>上面就是FBV的使用。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。