@csrf_exempt 不适用于基于通用视图的类 [英] @csrf_exempt does not work on generic view based class

查看:32
本文介绍了@csrf_exempt 不适用于基于通用视图的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class ChromeLoginView(View):

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

     @method_decorator(csrf_exempt)
     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})

我希望帖子确实被 csrf 停止,但它返回 403 错误.

I am expecting that the post does stopped by csrf, but it return 403 error.

但是如果删除那个装饰器并在 URLConf 中执行此操作

But if remove that decorator and do this in the URLConf

url(r'^chrome_login/', csrf_exempt(ChromeLoginView.as_view()), name='chrome_login'),

它会起作用.

这里发生了什么?它不应该工作,因为我想这就是 method_decorator 所做的.我正在使用 python3.4 和 django1.7.1

What happened here? didn't it supposed to work, because I guess that's what method_decorator do. I'm using python3.4 and django1.7.1

任何建议都会很棒.

推荐答案

正如@knbk 所说,这是必须要装饰的 dispatch() 方法.

As @knbk said, this is the dispatch() method that must be decorated.

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

Since Django 1.9, you can use the method_decorator directly on a class:

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() 方法只是为了装饰它.

This avoids overriding the dispatch() method only to decorate it.

这篇关于@csrf_exempt 不适用于基于通用视图的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆