drf 验证接口权限

解决方案

  • 引用 BasePermission
from rest_framework.permissions import BasePermission
  • 检查用户是否登录
# 检查用户是否登录
class CheckUserIsLoginPermission(BasePermission):

    def has_permission(self, request, view):
        token = request.META.get('HTTP_TOKEN')
        if token == '123456':
            return True
        return False
  • 视图实现
from rest_framework.views import APIView
from rest_framework.response import Response
from django_redis import get_redis_connection
from utils.helper import CheckUserIsLoginPermission


# 购物车
class CartView(APIView):
    permission_classes = [CheckUserIsLoginPermission,]

    def __init__(self):
        self.conn = get_redis_connection()


    def get(self,request):
        data = self.conn.hgetall('cart_2')
        return Response({"msg":"","data":data})
  • 请求数据
  1. token故意输错

  2. token输入正确

posted @ 2020-06-04 22:40  巫小诗  阅读(271)  评论(0编辑  收藏  举报