【问题标题】:Why is `csrf_exempt` not needed when using django-rest-framework?为什么使用 django-rest-framework 时不需要 `csrf_exempt`?
【发布时间】:2022-01-13 23:32:30
【问题描述】:

当我使用 Postman 发出 POST 请求时,我收到错误 Forbidden (CSRF cookie not set.)

class BooksView(View):
    def post(self, request):

如果我使用csrf_exempt,则不会发生错误

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt

@method_decorator(csrf_exempt, name='dispatch')
class BooksView(View):
    def post(self, request):

但是,当我使用django-rest-framework时,根本不会出现这个错误

from rest_framework.views import APIView

# /books
class BooksView(APIView):
    def post(self, request):

django-rest-frameworkAPIView 类相对于 csrf 做了什么?

【问题讨论】:

    标签: django django-rest-framework django-views csrf django-csrf


    【解决方案1】:

    django-rest-framework 中的所有视图和视图集都继承自APIView,这个类用csrf_exempt in the as_view method 包裹自己。

    【讨论】:

      猜你喜欢
      • 2018-02-26
      • 2016-10-31
      • 2016-07-27
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      相关资源
      最近更新 更多