zoukankan      html  css  js  c++  java
  • 11 Django REST Framework 针对基于类的视图添加 @csrf_exempt

    01-在类的 dispatch 方法上使用 @csrf_exempt

    from django.views.decorators.csrf import csrf_exempt
    
    class MyView(View):
    
        def get(self, request):
            return HttpResponse("hi")
    
        def post(self, request):
            return HttpResponse("hi")
    
        @csrf_exempt
        def dispatch(self, *args, **kwargs):
            return super(MyView, self).dispatch(*args, **kwargs)

    02-在 urls.py 中配置

    from django.conf.urls import url
    from django.views.decorators.csrf import csrf_exempt
    import views
    
    urlpatterns = [
        url(r'^myview/$', csrf_exempt(views.MyView.as_view()), name='myview'),
    ]

    03-重新改写其中验证 csrf 的方法

    在之前,我们对于 csrf 的处理都是使用的 csrf_exempt ,现在我们的 API 都是使用 Router 来生成了。该怎么办呢?
    在 Django 中,一个请求在到达视图之前,会先经过中间件的处理。在 DRF 中,所有的请求会先经过认证处理,如果请求认证通过,则会让请求访问视图,如果认证不通过,请求就无法到达视图。所以,我们采用的方法是重写认证。
    在 APIView 中,如果提供了 authentication_classes ,则会使用提供的认证后端来进行认证。如果没有提供,则会使用默认的认证后端。有关的细节我们将会在之后的章节中讨论,大家就先了解到这里。提供 csrf 验证的是一个叫做 SessionAuthentication 的认证后端,我们需要重新改写其中验证 csrf 的方法。
    # views.py
    
    from rest_framework.authentication import SessionAuthentication
    
    
    class CsrfExemptSessionAuthentication(SessionAuthentication):
        """
        去除 CSRF 检查
        """
    
        def enforce_csrf(self, request):
            return
    
    
    class MsgCodeViewSet(CreateModelMixin, viewsets.GenericViewSet):
    
        serializer_class = MsgCodeSerializer
        pagination_class = StandardResultsSetPagination
    
        # 
        authentication_classes = (CsrfExemptSessionAuthentication, )
        permission_classes = (AllowAny, )
  • 相关阅读:
    LeetCode题目(python)
    解决:centos配置ssh免密码登录后仍要输入密码
    解决 find: 路径必须在表达式之前:
    --解决Lock wait timeout exceeded; try restarting transaction
    Linux文件删除,但是df之后磁盘空间没有释放
    定位class时空格注意
    解决jenkins的Console Output中文乱码
    CPU飙升问题排查
    JVM笔记
    List集合的使用
  • 原文地址:https://www.cnblogs.com/pgxpython/p/10683474.html
Copyright © 2011-2022 走看看