page contents

Django中的一些概念和使用技巧

Django中模式概念 FBV: function basic view def home(request): return HttpResponse() CBV: class basic view class HomeView(View): def get(self, request): return HttpR...

Django中模式概念

FBV: function basic view

def home(request):    return HttpResponse()

CBV: class basic view

class HomeView(View):    def get(self, request):        return HttpResponse()

Django中间件

Django中间件的五个方法方法

  • process_request
  • process_response
  • process_view
  • process_exception
  • process_render_template

执行顺序:请求过来

  1. 执行所有中间件的process_request
  2. 执行路由匹配,找到要执行的函数
  3. 执行所有中间件的process_view
  4. 执行路由匹配到的函数
  5. 执行process_response如果响应的执行有异常就执行process_exception如果路由函数中有render渲染HTML,则先执行process_render_template,再执行process_response

Django CSRF验证

Django的crsf验证是在中间件CsrfViewMiddleware中进行验证的,具体来讲是在此中间件的process_view中验证的。那么为什么要在process_view中验证而不是在process_request中呢?我们先了解一个情况,如果我不希望某个路由函数进行csrf验证,可以加上csrf_exempt,免除csrf验证,所有必须在process_view中验证,而不是在process_request中。

from django.views.decorators.csrf import csrf_exempt@csrf_exemptdef home(request):    return HttpResponse()

如果是在CBV中要取消某个路由的csrf验证呢?

from django.view.decorators.csrf import csrf_exemptfrom django.utils.decorators import method_decoratorclass HomeView(View):    @method_decorator(csrf_exempt)    def dispatch(self, request, *args, **kwargs):        return super().dispatch(request, *args, **kwargs)    def post(self, request):        return HttpResponse()或者@method_decorator(csrf_exempt, name="dispatch")class HomeView(View):    pass

必须使用method_decorator装饰器修饰,并且只能添加到dispatch中,加到单独的函数中是不行的。

rest_framework中的APIView

BaseAuthentication.authenticate方法返回值:None: 执行下一个认证非None: 验证通过抛出异常:验证不通过
  • 发表于 2020-02-19 14:48
  • 阅读 ( 586 )
  • 分类:Python开发

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
Pack
Pack

1135 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. 小柒 1312 文章
  3. Pack 1135 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章