Django-CBV
CBV(class base views):python是一个面向对象的编程语言,如果只用函数来开发,有很多面向对象的优点就错失了(继承、封装、多态)。所以Django在后来加入了Class-Based-View。可以让我们用类写view,这样做的优点主要有:
(1)提高了代码的复用性,可以使用面向对象的技术,比如Mixin
(2)可以用不同的函数针对不同的HTTP方法处理,而不是通过很多if判断,提高代码可读性
如果我们要写一个处理GET方法的view,用FBV(function base views)即在视图中用函数处理请求的话是这样
from django.shortcuts import render,HttpResponse def my_view(request): if request.method=='GET': return HttpResponse('OK')
如果用CBV写的话就是这样:
from django.shortcuts import render,HttpResponse from django.views import View class MyView(View): def get(self,request): return HttpResponse('OK')
Django的url是将一个请求分配给可调用的函数的,而不是一个class。针对这个问题,CBV提供了一个as_view()静态方法(也就是类方法),调用这个方法,会创建一个类的实例,然后通过实例调用dispatch()方法,dispatch()方法会根据request的method的不同调用响应的方法来处理request,如果方法没有定义,会抛出HttpResponseAllowed异常
在url中,就这么写
from django.conf.urls import url from django.contrib import admin from app01.views import MyView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/$', MyView.as_view()), ]
类的属性可以通过两种方法设置,第一种是python常用方法,可以被子类覆盖
from django.shortcuts import render,HttpResponse from django.views import View class Pview(View): name='lary' def get(self,request): return HttpResponse(self.name) class Sview(View): name='lily'
也可以在url中指定类的属性
from django.conf.urls import url from django.contrib import admin from app01.views import * urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'login',Sview.as_view(name='jary')), ]
csrf认证
#方式一 from django.shortcuts import render,HttpResponse import json from django.views import View from django.views.decorators.csrf import csrf_exempt,csrf_protect from django.utils.decorators import method_decorator # Create your views here. class StudentsView(View): @method_decorator(csrf_exempt()) def get(self,request,*args,**kwargs): return HttpResponse('GET') def post(self,request,*args,**kwargs): return HttpResponse('POST') def put(self,request,*args,**kwargs): return HttpResponse('PUT') def delete(self,request,*args,**kwargs): return HttpResponse('DELETE')
#方式二 from django.shortcuts import render,HttpResponse import json from django.views import View from django.views.decorators.csrf import csrf_exempt,csrf_protect from django.utils.decorators import method_decorator # Create your views here. @method_decorator(csrf_exempt,name='dispatch') class StudentsView(View): def get(self,request,*args,**kwargs): return HttpResponse('GET') def post(self,request,*args,**kwargs): return HttpResponse('POST') def put(self,request,*args,**kwargs): return HttpResponse('PUT') def delete(self,request,*args,**kwargs): return HttpResponse('DELETE')