为啥使用 django-rest-framework 时不需要 `csrf_exempt`?

Posted

技术标签:

【中文标题】为啥使用 django-rest-framework 时不需要 `csrf_exempt`?【英文标题】: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-framework 和 APIView 类相对于 csrf 做了什么?

【问题讨论】:

【参考方案1】:

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

【讨论】:

以上是关于为啥使用 django-rest-framework 时不需要 `csrf_exempt`?的主要内容,如果未能解决你的问题,请参考以下文章