Django 之 restframework 频率组件的使用

it2022-05-07  43

Django 之 restframework 频率组件的使用以及源码分析

频率组件的使用

第一步,先写一个频率类,继承SimpleRateThrottle

一定要在这个类里面配置一个scop=‘字符串’--->字符串用于settings里面配置频率组件在该类里面重写 get_cache_key, 返回self.get_ident(request)from rest_framework.throttling import SimpleRateThrottle # 创建一个频率类 class Throttle(SimpleRateThrottle): # 在频率类中配置一个scope scope='qzk' # 重写 该类中的 get_cache_key 方法 def get_cache_key(self,request,view): # 返回 self.get_ident(request) return self.get_ident(request)

第二步,在settings.py文件中配置 频率组件

# 全局使用认证、权限组件、频率组件 REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ["app01.auths.MyAuth", ], # 全局认证组件配置 "DEFAULT_PERMISSION_CLASSES": ["app01.permissions.MyPermission", ], # 全局权限组件配置 'DEFAULT_THROTTLE_CLASSES': ['app01.throttles.RateThrottle', ], # 频率组件全局配置 'DEFAULT_THROTTLE_RATES': { 'qzk': '3/m' # 控制访问频率为一分钟三次 } # }

第三步,在视图类中使用频率组件

局部使用:在视图类中,配置 throttle_classes=[RateThrottle,]from rest_framework.views import APIView from rest_framework.response import Response from app01 import models from app01.myser import BookSerializer # 导入序列化组件 from app01 import auths # 导入认证组件 from app01 import throttles # 导入频率组件 from app01 import permissions # 导入权限组件 class Book(APIView): """局部使用三个认证、权限、频率""" # 配置认证类列表 authentication_classes = [auths.MyAuth, ] # 配置权限类列表 permission_classes = [permissions.MyPermission, ] # 配置评率认证列表 throttle_classes = [throttles.RateThrottle, ] # get 获取所有书籍信息 def get(self, request, id): response = {'status': 100, 'msg': '成功'} print(id) if not id: book_list = models.Book.objects.all() # 第一个参数是要序列化的queryset对象,如果要序列化多条,必须制定many=True # 当instance形参被传入的实参是单个参数的时候,many=False book_serializer = BookSerializer(book_list, many=True) else: print(id) book_obj = models.Book.objects.filter(pk=id).first() book_serializer = BookSerializer(book_obj, many=False) print(book_serializer.data) response['books'] = book_serializer.data return Response(response) """新增功能""" def post(self, request, id): response = {'status': 100, 'msg': '成功'} # 提交的字典 book = request.data # 传统方法,创建对象保存 print(book) # 新方法,通过序列化组件保存,必须继承自ModelSerializer book_ser = BookSerializer(data=book) # is_valid 提交的字段校验通过 if book_ser.is_valid(): book_ser.save() response['book'] = book_ser.data else: response['msg'] = book_ser.errors # errors 是序列化类 中的钩子函数 raise来的报错信息 return Response(response) """修改功能""" def put(self, request, id): response = {'status': 100, 'msg': '修改成功'} if id: # 提交的字典 book = request.data # 传统方法,创建对象保存 print(book) book_obj = models.Book.objects.filter(pk=id).first() # 新方法,通过序列化组件保存,必须继承自ModelSerializer book_ser = BookSerializer(data=book, instance=book_obj) # is_valid 提交的字段校验通过 if book_ser.is_valid(): # 这里save()做修改 book_ser.save() response['book'] = book_ser.data else: response['msg'] = book_ser.errors else: response['msg'] = '修改对象不存在' return Response(response) """删除功能""" def delete(self, request, id): models.Book.objects.filter(pk=id).delete() response = {'status': 100, 'msg': '删除成功'} return Response(response) from django.core.exceptions import ObjectDoesNotExist import uuid """用户登录类""" class Login(APIView): # 局部禁用认证组件 authentication_classes = [] # 局部禁用权限组件 permission_classes = [] # 局部禁用频率组件 throttle_classes = [] def post(self, request): response = {'code': 100, 'msg': '登录成功'} name = request.data.get('name') pwd = request.data.get('pwd') print(name, pwd) try: # get()方法,获取 有且只有一条的 才不报错,其他情况都抛异常 ret = models.User.objects.filter(name=name, pwd=pwd).get() # 登录成功后要去token 表中去存数据 # 表里有 数据或没有数据 # 1. 先生成随机字符串 用uuid token = uuid.uuid4() # 2. 存入token表 # update_or_create() 方法 先查后改,查到就修改,没查到就新增 根据 user 去查 models.Token.objects.update_or_create(user=ret, defaults={'token': token}) response['token'] = token except ObjectDoesNotExist as exc: response['code'] = 101 response['msg'] = '用户名或密码错误' except Exception as e: response['code'] = 102 response['msg'] = str(e) return Response(response) 全局使用:在settings文件中配置 DEFAULT_THROTTLE_CLASSES# 全局使用认证、权限组件、频率组件 REST_FRAMEWORK = { # 全局认证组件配置 "DEFAULT_AUTHENTICATION_CLASSES": ["app01.auths.MyAuth", ], # 全局权限组件配置 "DEFAULT_PERMISSION_CLASSES": ["app01.permissions.MyPermission", ], # 频率组件全局配置 'DEFAULT_THROTTLE_CLASSES': ['app01.throttles.RateThrottle', ], # 控制访问频率为一分钟三次 'DEFAULT_THROTTLE_RATES': { 'qzk': '3/m' # 这里的'qzk' 是根据频率校验类中的scope决定的,两者保持一致 } # } 局部禁用:在需要禁用的视图类中 将配置的throttle_classes = [ ] 置空class Book(APIView): """局部使用三个认证、权限、频率""" # 局部禁用认证校验组件 authentication_classes = [] # 局部禁用权限校验组件 permission_classes = [] # 局部禁用频率校验组件 throttle_classes = []

补充models.py

from django.db import models # Create your models here. class Book(models.Model): title = models.CharField(max_length=32) price = models.DecimalField(max_digits=8, decimal_places=2) publish_time = models.DateTimeField(auto_now_add=True) # 自动添加创建时间 authors = models.ManyToManyField('Author') publish = models.ForeignKey('Publish') # 一对多 def test(self): return self.title + '>>' + str(self.price) class Author(models.Model): name = models.CharField(max_length=32) age = models.IntegerField() authordetail = models.OneToOneField('AuthorDetail') class AuthorDetail(models.Model): tel_num = models.BigIntegerField() addr = models.CharField(max_length=32) class Publish(models.Model): name = models.CharField(max_length=32) addr = models.CharField(max_length=32) email = models.EmailField() class User(models.Model): name = models.CharField(max_length=32) pwd = models.CharField(max_length=32) user_type = models.IntegerField(choices=((1, '超级用户'), (2, '普通用户'), (3, '游客')),default=3) class Token(models.Model): user = models.OneToOneField(to='User') token = models.CharField(max_length=64)

urls.py

from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^books/(?P<id>\d*)',views.Book.as_view()), url(r'^login/',views.Login.as_view()) ]

转载于:https://www.cnblogs.com/qianzhengkai/p/11133363.html

相关资源:Django REST Framework之频率限制的使用

最新回复(0)