在基于类的视图上使用装饰器会导致AttributeE

2024-09-28 23:39:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为ChannelAuth的基于类的视图,出于测试目的,我们用@csrf_exempt修饰了它。这不是最后的决定,但是为了学习,我还是想要一个答案

@csrf_exempt
class ChannelAuth(views.APIView):
    def post(self, request, *args, **kwargs):
        if not request.data:
            return JsonResponse({'Error': 'Data is malformed.'}, status=400)
....

但是,当使用装饰器时,我们可以说是在函数中“包装”类

这意味着当我们使用ChannelAuth.as_view()时,实际上并没有像预期的那样访问as_view()属性,因为它在“包装函数”中不存在,因此抛出了AttributeError

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/auth/channels/', ChannelAuth.as_view(), name="channel_auth")
    ]

所以我的问题是,如何在基于类的视图上正确地使用@csrf_exempt这样的装饰器


Tags: path函数答案目的authview视图admin
1条回答
网友
1楼 · 发布于 2024-09-28 23:39:34

最初的解决方案是在目标方法上使用Django的^{}

from django.utils.decorators import method_decorator

class ChannelAuth(views.APIView):
    @method_decorator(csrf_exempt, name='post')
    def post(self, request, *args, **kwargs):
        if not request.data:
            return JsonResponse({'Error': 'Data is malformed.'}, status=400)
....

相关问题 更多 >