您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

@csrf_exempt在基于通用视图的类上不起作用

@csrf_exempt在基于通用视图的类上不起作用

你需要装饰工作dispatch方法csrf_exempt。它所做的是将csrf_exempt视图函数本身的属性设置为True,然后中间件在(最外面的)视图函数中对此进行检查。如果只需要修饰几种方法,则仍然需要csrf_exempt在该dispatch方法上使用,但是可以csrf_protect在例如上使用put()。如果GET,HEAD,OPTIONSTRACE使用HTTP方法不管你把装修与否也不会被选中。

class ChromeLoginView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(ChromeLoginView, self).dispatch(request, *args, **kwargs)

    def get(self, request):
        return JsonResponse({'status': request.user.is_authenticated()})

    def post(self, request):
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return JsonResponse({'status': True})
        return JsonResponse({'status': False})

这是dispatch()必须修饰的方法

从Django 1.9开始,你可以method_decorator直接在类上使用:

from django.utils.decorators import method_decorator

@method_decorator(csrf_exempt, name='dispatch')
class ChromeLoginView(View):

    def get(self, request):
        return JsonResponse({'status': request.user.is_authenticated()})

    def post(self, request):
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return JsonResponse({'status': True})
        return JsonResponse({'status': False})

这避免了dispatch()仅装饰方法的重写方法

其他 2022/1/1 18:23:19 有595人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶