DRF之权限认证频率组建

认证组件

  很久很久以前,Web站点只是作为浏览服务器资源(数据)和其他资源的工具,甚少有什么用户交互之类的烦人的事情需要处理,所以,Web站点的开发这根本不关心什么人在什么时候访问了什么资源,不需要记录任何数据,有客户端请求,我即返回数据,简单方便,每一个http请求都是新的,响应之后立即断开连接。而现在不同,现在的时代已经不能没有用户了,所以随之而来的就是用户交互,之前对于用户认证的我们cookies和secess都可以,但是相对于我们今天学的token而言,市面上还是说token用的比较多一点,所以,token!!!你们懂了吧,嘿嘿好了,废话不说了直接上干货

  1.创建表

  

model.py

from django.db import models

# Create your models here.


class User(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
    user_type_entry = (
        (1, 'Delux'),
        (2, 'SVIP'),
        (3, "VVIP")
    )
    user_type = models.IntegerField(choices=user_type_entry)
    address = models.CharField(max_length=32)

    def __str__(self):
        return self.username


class UserToken(models.Model):
    user = models.OneToOneField("User", on_delete=models.CASCADE)
    token = models.CharField(max_length=128)

2.urls

re_path(r'user/$', views.UserView.as_view()),

  

3.涉及用户交互的行为只有post请求的时候才会有,所以我们只需要写post请求就可以了,get请求我们不必写

views.py

from django.http import JsonResponse

from rest_framework.views import APIView

from .models import User, Book, UserToken
from .utils import get_token


class UserView(APIView):

    def post(self, request):
        response = dict()
        try:
       #因为所有的数据都在request.data中,所以我们取得时候就直接在data中取
            username = request.data['username']
            password = request.data['password']

            user_instance = User.objects.filter(
                user_name=username,
                password=password
            ).first()

      #get_token.generater_token() 这里使我们随机产生的token值,我们需要在下一步中引用一下
            if user_instance:
                access_token = get_token.generater_token()

                UserToken.objects.update_or_create(user=user_instance, defaults={
                    "token": access_token
                })
                response["status_code"] = 200
                response["status_message"] = "登录成功"
                response["access_token"] = access_token
                response["user_role"] = user_instance.get_user_type_display()
            else:
                response["status_code"] = 201
                response["status_message"] = "登录失败,用户名或密码错误"
        except Exception as e:
            response["status_code"] = 202
            response["status_message"] = str(e)

        return JsonResponse(response)

4.新建utils文件夹

import uuid


def generater_token():
    random_str = ''.join(str(uuid.uuid4()).split('-'))
    return random_str

5.完美,现在一个简单的token就已经创建完了,下面,开始我们认证组建的使用

6.第一步:新建一个认证类

from rest_framwork.authentication import BaseAuthentication
from rest_framwork.exceptions import APIException

#. 代表往上走一层,或者你可以直接写你自己的当前程序
from .model import UserToken
views.py

#权限类
class UserPerm():
    message = "您没有查看该数据的权限!"

    def has_permission(self, request, view):
#这里的3就是我们新建表中的数据
        if request.user.user_type == 3:
            return True
        return False





class BookView(ModelViewSet):
#指定认证类
    authentication_class = [UserAuth]
#指定权限类
    permission_classes= [UserPerm]
    
#序列化
    queryset = Book.objects.all()
    serializer_class = BookSerializer


class UserAuth(BaseAuthentication):

#这里注意,认证类中必须有authenticate这个方法!!!为啥?看源码
    def authenticate(self,request):
        user_token = request.query_params.get('token')
#一定要记得try
        try:
            token = UserToken.objects.get(token = user_token)
            return token.user,token.token
        except Exception as e:
            raise APIException('没有认证')

 频率组件

1.写频率类

from rest_framework.throttling import SimpleRateThrottle

#必须继承SimpleRateThrottle这个类
class RateThrottle(SimpleRateThrottle):
    rate = '5/m'

    def get_cache_key(self, request, view):
#这里是通过id来控制访问的频率
        return self.get_ident(request)

2.指定频率类

from .utils.throttles import RateThrottle

# Create your views here.


class BookView(ModelViewSet):
    throttle_classes = [ RateThrottle ]
    queryset = Book.objects.all()
    serializer_class = BookSerializer

3.用!!!

 好了。现在我们的基本就实现了,后期还会有补充哦

      参考网址;https://pizzali.github.io/2018/12/07/DRF%E4%B9%8B%E6%9D%83%E9%99%90%E8%AE%A4%E8%AF%81%E9%A2%91%E7%8E%87%E7%BB%84%E4%BB%B6/

  

原文地址:https://www.cnblogs.com/lzqrkn/p/10100739.html