Rest_Framework之频率组件部分
一、RestFramework之频率组件源码部分
频率组件的源码部分和权限组件流程一模一样的,这里就不多说了,直接上源码的主要逻辑部分:
def check_throttles(self, request):
"""
Check if request should be throttled.
Raises an appropriate exception if the request is throttled.
"""
for throttle in self.get_throttles():
if not throttle.allow_request(request, self):
self.throttled(request, throttle.wait())
明确表示我们写的频率类需要一个allow_request()方法:
频率类(完成一分钟同一个ip只能访问三次):
import time
from rest_framework.throttling import BaseThrottle class MyThrottle(BaseThrottle):
visited_record = {} def __init__(self):
self.history = None def allow_request(self, request, my_cbv): # 这个my_cbv是源码中传的我们的视图类,这里我们也要传进去
# print(self.get_ident(request)) # 可以获取本次请求的ip
ip = request.META.get("REMOTE_ADDR")
if ip not in self.visited_record:
self.visited_record[ip] = [] current_time = time.time()
history = self.visited_record[ip]
self.history = history while history and current_time - history[-1] > 60: # 把与当前访问时间相差大于60秒的时间都删掉
history.pop() if len(history) > 2: # 第三次访问,列表中只有2个值,也满足条件,大于2个值时不满足条件
return False
history.insert(0, current_time)
return True def wait(self):
"""
用于返回还剩多少时间访问; 本次访问时间:9:50:55
[09:50:30, 09:50:20, 09:50:10] 剩余 60 - (9:50:55 - 09:50:10)秒才能访问
:return:
"""
c_time = time.time()
return 60 - (c_time - self.history[-1])
视图类:
class BookView(ModelViewSet):
authentication_classes = [UserAuth] #认证类
permission_classes = [UserPerm] #权限类
throttle_classes = [MyThrottle] #频率类
queryset = Book.objects.all()
serializer_class = BookSerializer
效果如下:

可以在全局settings配置
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
),
'DEFAULT_AUTHENTICATION_CLASSES':
'app01.utils.auth_class.UserAuth',
),
'DEFAULT_PERMISSION_CLASSES': (
'app01.utils.permission_class.VipPermission',
),
'DEFAULT_THROTTLE_CLASSES': (
'app01.utils.throttle_class.MyThrottle',
),
}
二、使用restframework组件中的提供的访问限制
实现方式和我们上面的方式基本相同;
基于限制ip的类:SimpleRateThrottle
基于ip的访问限制:
频率类——局部:
from rest_framework.throttling import SimpleRateThrottle
class MyThrottle(SimpleRateThrottle):
rate = '5/m'
def get_cache_key(self, request, view): # 这个方法也是必须要有
return self.get_ident(request)
在视图类中指定频率类
class BookView(ModelViewSet):
throttle_classes = [app_throttles.RateThrottle]
queryset = Book.objects.all()
serializer_class = BookSerializer
duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}
频率类——全局:
from rest_framework.throttling import SimpleRateThrottle
class MyThrottle(SimpleRateThrottle):
scope = "visit_rate" # 这个值决定了在配置时使用哪个变量描述限制的频率,必须在settings里面配置
def get_cache_key(self, request, view): # 这个方法也是必须要有
return self.get_ident(request)
这次只能在setttings中配置:
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'app01.utils.throttle_class.MyThrottle',
),
"DEFAULT_THROTTLE_RATES": {
"visit_rate": "10/m", # 这个参数就是频率类中定义的那个参数scope, 其中第一个数字10表示10次,后面的m表示一分钟,还有s,一秒, h, 一小时, d, 一天
}
}
duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}
Rest_Framework之频率组件部分的更多相关文章
- Django的rest_framework的权限组件和频率组件源码分析
前言: Django的rest_framework一共有三大组件,分别为认证组件:perform_authentication,权限组件:check_permissions,频率组件:check_th ...
- Rest_Framework之认证、权限、频率组件源码剖析
一:使用RestFramwork,定义一个视图 from rest_framework.viewsets import ModelViewSet class BookView(ModelViewSet ...
- DjangoRestFramework学习三之认证组件、权限组件、频率组件、url注册器、响应器、分页组件
DjangoRestFramework学习三之认证组件.权限组件.频率组件.url注册器.响应器.分页组件 本节目录 一 认证组件 二 权限组件 三 频率组件 四 URL注册器 五 响应器 六 分 ...
- 前后端分离djangorestframework——限流频率组件
频率限制 什么是频率限制 目前我们开发的都是API接口,且是开房的API接口.传给前端来处理的,也就是说,只要有人拿到这个接口,任何人都可以通过这个API接口获取数据,那么像网络爬虫的,请求速度又快, ...
- rest-framework频率组件
throttle(访问频率)组件 1.局部视图throttle from rest_framework.throttling import BaseThrottle VISIT_RECORD={} c ...
- rest_framework视图和组件
一.视图 1.基本视图 #基本视图 #抽取基类 from rest_framework.response import Response from rest_framework.views impor ...
- drf频率组件
1.简介 控制访问频率的组件 2.使用 手写一个自定义频率组件 import time #频率限制 #自定义频率组件,return True则可以访问,return False则不能访问 class ...
- day91 DjangoRestFramework学习三之认证组件、权限组件、频率组件、url注册器、响应器、分页组件
DjangoRestFramework学习三之认证组件.权限组件.频率组件.url注册器.响应器.分页组件 本节目录 一 认证组件 二 权限组件 三 频率组件 四 URL注册器 五 响应器 六 分 ...
- DRF(5) - 频率组件、url注册器、响应器、分页器
一.频率组件 1.使用DRF简单频率控制实现对用户进行访问频率控制 1)导入模块,定义频率类并继承SimpleRateThrottle # 导入模块 from rest_framework.throt ...
随机推荐
- 【IT技术概念】WebAPI与传统的WebService有哪些不同?
在.net平台下,有大量的技术让你创建一个HTTP服务,像Web Service,WCF,现在又出了Web API.在.net平台下,你有很多的选择来构建一个HTTP Services.我分享一下我对 ...
- 【ADO.NET基础-数据加密】第一篇(加密解密篇)
可以采用下面的函数实现密码的加密 public static string EncryptString(string str) { //密文 string key = "www"; ...
- .Net Core自动化部署系列(三):使用GitLab CI/CD 自动部署Api到Docker
之前写过使用Jenkins实现自动化部署,最近正好没事研究了下GitLab的自动化部署,顺便记录一下. 使用GitLab部署我们需要准备两件事,第一个起码你得有个GitLab,自己搭建或者使用官方的都 ...
- 高效解决「SQLite」数据库并发访问安全问题,只这一篇就够了
Concurrent database access 本文译自:https://dmytrodanylyk.com/articles/concurrent-database/ 对于 Android D ...
- VR应用评测 - Apollo 11 阿波罗11号
Apollo 11 VR http://store.steampowered.com/app/457860/Apollo_11_VR/ Steam VR 2016年发布 好评率 50% 基于美国航空航 ...
- Openshift yum安装
Openshift yum安装: Yum 安装docker [root@DockerServer openshift]# yum repolist [root@DockerServer openshi ...
- 本人亲测-SSM环境搭建(使用eclipse作为示例,过程挺全的,可作为参考)
本人亲测-SSM环境搭建(使用eclipse作为示例,过程挺全的,可作为参考) 本人亲测-SSM环境搭建(使用eclipse作为示例,过程挺全的,可作为参考) 本人亲测-SSM环境搭建(使用eclip ...
- MySQL学习(二)索引原理及其背后的数据结构
首先区分几个概念: 聚集索引 主索引和辅助索引(即二级索引) innodb中每个表都有一个聚簇索引(clustered index ),除此之外的表上的每个非聚簇索引都是二级索引,又叫辅助索引(sec ...
- Java ThreadLocal 的使用与源码解析
GitHub Page: http://blog.cloudli.top/posts/Java-ThreadLocal-的使用与源码解析/ ThreadLocal 主要解决的是每个线程绑定自己的值,可 ...
- 代码审计准备之Thinkphp3
0x01环境部署: 下载: 获取ThinkPHP的方式很多,官方网站(http://thinkphp.cn)是最好的下载和文档获取来源. 官网提供了稳定版本的下载:http://thinkphp.cn ...