FBV/CBV
作者:互联网
CBV、FBV
基于反射实现根据请求方式不同,执行不同的方法
原理看源码:url->view->dispatch(反射执行其他:['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'])
1 from django.shortcuts import render, HttpResponse 2 from django.views import View 3 from django.views.decorators.csrf import csrf_exempt 4 5 6 @csrf_exempt 7 def userinfo(request): 8 import json 9 user_list = ['悟空', '三藏'] 10 return HttpResponse(json.dumps(user_list)) 11 12 from django.utils.decorators import method_decorator 13 14 15 class MybaseView(object): 16 17 def dispatch(self, request, *args, **kwargs): 18 print('before') 19 ret = super(MybaseView, self).dispatch(request, *args, **kwargs) 20 print('after') 21 return ret 22 23 24 @method_decorator(csrf_exempt, name='dispatch') 25 class StudentView(MybaseView, View): 26 27 def get(self, request, *args, **kwargs): 28 print('get') 29 return HttpResponse('GET') 30 31 def post(self, request, *args, **kwargs): 32 return HttpResponse('POST') 33 34 def put(self, request, *args, **kwargs): 35 return HttpResponse('PUT') 36 37 def delete(self, request, *args, **kwargs): 38 return HttpResponse('DELTEE') 39 40 41 @method_decorator(csrf_exempt, name='dispatch') 42 class TeacherView(MybaseView, View): 43 44 def get(self, request, *args, **kwargs): 45 return HttpResponse('GET') 46 47 def post(self, request, *args, **kwargs): 48 return HttpResponse('POST') 49 50 def put(self, request, *args, **kwargs): 51 return HttpResponse('PUT') 52 53 def delete(self, request, *args, **kwargs): 54 return HttpResponse('DELTEE')
我这样继承可以相当于给类里边的方法加上装饰器的效果
执行流程图:
标签:return,FBV,args,request,CBV,kwargs,HttpResponse,def 来源: https://www.cnblogs.com/Alexephor/p/11257993.html