Django基础之CBV
CBV:Class Based View
FBV:Function Based View
我们之前写过的都是基于函数的view,就叫FBV。还可以把view写成基于类的,那就是CBV。
一:FBV
1.1 FBV简单使用
视图函数:
def login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
if username == 'root' and password == 'root':
return HttpResponse('login success')
return render(request, 'login.html')
路由配置:
urlpatterns = [
path('login/', views.login),
]
1.2 FBV装饰器
FBV本身就是一个函数,所以和给普通的函数加装饰器无差
def timer(func):
def inner(request, *args, **kwargs):
start_time = time.time()
time.sleep(1)
resp = func(request, *args, **kwargs)
end_time = time.time()
print(end_time - start_time)
return resp
return inner
@timer
def login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
if username == 'root' and password == 'root':
return HttpResponse('login success')
return render(request, 'login.html')
二:CBV
2.1 CBV简单使用
视图类:
from django.views import View
class LoginView(View):
def get(self, request):
return render(request, 'login.html')
def post(self, request):
username = request.POST.get('username')
password