gpt4 book ai didi

python - @csrf_exempt 不适用于基于通用 View 的类

转载 作者:IT老高 更新时间:2023-10-28 20:32:19 25 4
gpt4 key购买 nike

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 错误。

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

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

它会起作用的。

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

任何建议都会很棒。

最佳答案

正如@knbk所说,这是必须修饰的dispatch()方法。

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

关于python - @csrf_exempt 不适用于基于通用 View 的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27315592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com