drf---自定义认证类&同一个类中get/post使用两个不同的认证类

1. 自定义认证类

认证详解https://blog.csdn.net/qq_52385631/article/details/123022575?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522164597980116780265454589%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=164597980116780265454589&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-1-123022575.nonecase&utm_term=%E8%AE%A4%E8%AF%81&spm=1018.2226.3001.4450

1.1 view

from api import models

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed


class PublicAuthentication(BaseAuthentication):
    """普通校验,记录登录的用户"""

    def authenticate(self, request):
        # 请求头取数据,都是HTTP_大写(在django)
        token = request.META.get('HTTP_AUTHORIZATION')
        # 在认证组件中,如果返回一个None,是交给下一个组件处理
        if not token:
            return None
        user_obj = models.UserInfo.objects.filter(token=token).first()
        if not user_obj:
            return None
        return (user_obj, token)  # request.user/auth


class LoginAuthentication(BaseAuthentication):
    """必须登录认证"""

    def authenticate(self, request):
        # 请求头取数据,都是HTTP_大写(在django)
        token = request.META.get('HTTP_AUTHORIZATION')
        # 在认证组件中,如果返回一个None,是交给下一个组件处理
        if not token:
            raise AuthenticationFailed()  # 前端返回403
        user_obj = models.UserInfo.objects.filter(token=token).first()
        if not user_obj:
            raise AuthenticationFailed()
        return (user_obj, token)  # request.user/auth

1.2 settings

# rest_framework配置(全局)
REST_FRAMEWORK = {
    'UNAUTHENTICATED_USER': None,
    'UNAUTHENTICATED_TOKEN': None,
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'utils.auth.PublicAuthentication'
    ],

}

2. 同一个类中get/post使用两个不同的认证类

该类视图需要重写get_authenticators

from utils.auth import LoginAuthentication, PublicAuthentication


class CommentAPIView(APIView):
    """获取更多评论&保存数据"""

    def get_authenticators(self):
        # 重写认证类
        if self.request.method == 'POST':
            return [LoginAuthentication(), ]
        return [PublicAuthentication(), ]

    def get(self, request, *args, **kwargs):
        """获取更多评论,通过root"""
        print(request.user)
        root = int(request.query_params.get('root'))
        # print(root)
        queryset = models.Comment.objects.filter(root=root)
        # print(queryset)
        ser = CommentModelSerializer(instance=queryset, many=True)
        return Response(data=ser.data)

    def post(self, request, *args, **kwargs):
        """保存评论数据"""
        ser = PostCommentModelSerializer(data=request.data)  # ...
        # print(request.data)
        if ser.is_valid():
            ser.save(userinfo_id=1)
            # 评论数+1
            new_id = ser.validated_data.get('new').id
            models.Release.objects.filter(id=new_id).update(release_num=F('release_num') + 1)
            return Response(ser.data, status=status.HTTP_201_CREATED)
        return Response(ser.errors, status=status.HTTP_400_BAD_REQUEST)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

骑猪去兜风z1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值