from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_protect @csrf_exempt def users(request): user_list = ['alex', 'oldboy'] MIDDLEWARE = { } 小知识 CBV知识点, csrf时需要使用 -@method_decorator(csrf_exempt) -在dispatch方法中 (单独设置不行) from django.utils.decorators import method_decorator class StudentsView(View): @method_decorato(csrf_exempt) def dispatch(self,request, *args, **kwargs): return super(StudentsView, self).dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): return HttpResponse('POST') @method_decorator(csrf_exempt, name='dispatch') class StudentsView(View): def get(self, request, *args, **kwargs): pass 总结: 本质: 基于反射来实现 流程: 路由 view函数在到dispatch(反射) 取消csrf认证(装饰器要加到dispatch方法上且需要使用method_decorator装饰) 扩展: - csrf - 基于中间件的process_view方法 - 装饰器给单独函数进行设置 (认证/无需认证) FBV CBV 1.restful 规范 (建议) A 用户管理: http://www.oldboyedu.com/add_user/ 返回值: { code:123 } url(r^'order/', views.order) restful规范(建议) 第一条规范 对于订单(FBV) def order(request): #order 包含增删改查 if request.method == "GET": return HttpResponse("获取订单") if request.method == "POST" return HttpResponse("创建订单") if request.method == "PUT": return HttpResponse("更新订单") if request.method == "DEL": return HttpResponse("删除订单") 对于订单(CBV) url(r'^order/', views.OrderView.as_view()), class OrderView(View): def get(self, request, *args, **kwargs): return HttpResponse("获取订单") pass def post(self, request, *args, **kwargs): return HttpResponse("创建订单") pass def put(self, request, *args, **kwargs): return HttpResponse("更新订单") pass def delete(self, request, *args, **kwargs): return HttpResponse("删除订单") pass