11 Django REST Framework 针对基于类的视图添加 @csrf_exempt

01-在类的 dispatch 方法上使用 @csrf_exempt

from django.views.decorators.csrf import csrf_exempt

class MyView(View):

    def get(self, request):
        return HttpResponse("hi")

    def post(self, request):
        return HttpResponse("hi")

    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(MyView, self).dispatch(*args, **kwargs)

02-在 urls.py 中配置

from django.conf.urls import url
from django.views.decorators.csrf import csrf_exempt
import views

urlpatterns = [
    url(r'^myview/$', csrf_exempt(views.MyView.as_view()), name='myview'),
]

03-重新改写其中验证 csrf 的方法

在之前,我们对于 csrf 的处理都是使用的 csrf_exempt ,现在我们的 API 都是使用 Router 来生成了。该怎么办呢?
在 Django 中,一个请求在到达视图之前,会先经过中间件的处理。在 DRF 中,所有的请求会先经过认证处理,如果请求认证通过,则会让请求访问视图,如果认证不通过,请求就无法到达视图。所以,我们采用的方法是重写认证。
在 APIView 中,如果提供了 authentication_classes ,则会使用提供的认证后端来进行认证。如果没有提供,则会使用默认的认证后端。有关的细节我们将会在之后的章节中讨论,大家就先了解到这里。提供 csrf 验证的是一个叫做 SessionAuthentication 的认证后端,我们需要重新改写其中验证 csrf 的方法。
# views.py

from rest_framework.authentication import SessionAuthentication


class CsrfExemptSessionAuthentication(SessionAuthentication):
    """
    去除 CSRF 检查
    """

    def enforce_csrf(self, request):
        return


class MsgCodeViewSet(CreateModelMixin, viewsets.GenericViewSet):

    serializer_class = MsgCodeSerializer
    pagination_class = StandardResultsSetPagination

    # 
    authentication_classes = (CsrfExemptSessionAuthentication, )
    permission_classes = (AllowAny, )

 

转载于:https://www.cnblogs.com/pgxpython/p/10683474.html

from django.contrib.auth.models import User from django.contrib.auth import authenticate from django.http import HttpResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from rest_framework import status from rest_framework.templatetags.rest_framework import data from rest_framework.views import APIView from rest_framework.response import Response from app.scripts.mysql import Mysql from django.contrib.auth.hashers import make_password from rest_framework import serializers from rest_framework_simplejwt.tokens import RefreshToken from django.shortcuts import render from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import json from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import AllowAny from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from .models import LoginSerializer#UserProfileSerializer #def index(request): # import json #return HttpResponse("链接成功"), #Create your views here. class LoginView(APIView): authentication_classes = [SessionAuthentication] # 按需选择认证方式 permission_classes = [AllowAny] def post(self,request,*args,**kwargs): serializer = LoginSerializer(data=request.data) if not serializer.is_valid(): return Response({ 'code': 400, 'message': '参数错误', 'errors': serializer.errors }, status=status.HTTP_400_BAD_REQUEST) user = authenticate( username=serializer.validated_data['username'], password=serializer.validated_data['password'] ) if not user: return Response({ 'code': 401, 'message': '用户名或密码错误' }, status=status.HTTP_401_UNAUTHORIZED) refresh = RefreshToken.for_user(user) return Response({ 'code': 200, 'message': '登录成功', # 'data': { # 'user': UserProfileSerializer(user).data, #'access': str(refresh.access_token), # 'refresh': str(refresh) # } }) @csrf_exempt # 临时禁用CSRF验证(生产环境需替换为安全方案) def index(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') #打印到PyCharm控制台 print(f"接收到的数据:用户名={username}, 密码={password}") return JsonResponse({'status': 'success'}) return JsonResponse({'status': 'invalid method'}, status=400)这为上面报错的视图代码,结合上面的问题,看问题可能出在哪里
03-31
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值