- 路由系统
from django.urls import path
from app01.views import cbv_demo
urlpatterns = [
# path('admin/', admin.site.urls),
path('cbv/demo/', cbv_demo.StudentsView.as_view()),
]
- CBV视图
from django.views import View
from django.shortcuts import HttpResponse
from django.views.decorators.csrf import csrf_exempt,csrf_protect
from django.utils.decorators import method_decorator
"""
CBV知识点:
1.流程:路由--》view--》dispatch(反射)
2.取消csrf认证,有两种方式。重写dispatch,装饰dispatch。直接装饰类:@method_decorator(csrf_exempt,name='dispatch')
3.csrf认证,是基于中间件的process_view中实现。
中间件总共有5个方法,process_request,process_view,process_respones,process_exception,process_render_template
流程:执行所有的process_request--》》路由匹配--》》执行所有的process_view-->>视图函数--》》执行process——response
原因:我们在取消csrf认证的时候,加了装饰器-->>某个函数免除csrf认证--->>所以在认证的过程中需要判断函数有没有加装饰器--->>所以需要先做路由匹配,找到函数
"""
class MyBaseView(View):
# @method_decorator(csrf_exempt) # 1.免除csrf认证,必须在dispatch中使用在类中使用
def dispatch(self, request, *args, **kwargs):
print('before')
ret = super(MyBaseView,self).dispatch(request, *args, **kwargs)
print('after')
return ret
# @method_decorator(csrf_exempt,name='dispatch') # 2.直接装饰类
class StudentsView(MyBaseView,View):
def get(self,request,*args,**kwargs):
return HttpResponse('GET')
def post(self,request,*args,**kwargs):
return HttpResponse('POST')
def delete(self,request,*args,**kwargs):
return HttpResponse('DELETE')
def put(self,request,*args,**kwargs):
return HttpResponse('PUT')
class TeacherView(MyBaseView,View):
def get(self, request, *args, **kwargs):
return HttpResponse('GET')
def post(self, request, *args, **kwargs):
return HttpResponse('POST')
def delete(self, request, *args, **kwargs):
return HttpResponse('DELETE')
def put(self, request, *args, **kwargs):
return HttpResponse('PUT')
- 实现效果