第一版:

from rest_framework
class VisitThrottle(object):
def __init__(self):
self.history = None def allow_request(self,request,view):
#获取用户IP
#remote_addr = request.META.get('REMOTE_ADDR')
      remote_addr = self.get_ident(request)
ctime = time.time()
if remote_addr not in VISIT_RECORD:
VISIT_RECORD[remote_addr] = [ctime,]
return True
history = VISIT_RECORD.get(remote_addr)
self.history = history
while history and history[-1] < ctime - 10: #限制10秒内访问3次
history.pop()
if length(history) < 3:
history.insert(0,ctime)
return True #return False 表示访问频率过高 限制访问 def wait(self): #等待多少秒 才能继续访问
ctime = time.time()
return 60 - (ctime - self.history[-1]) class OrderView(APIView):
"""
订单业务
""" authentication_classes = []
permission_classes = []
throttle_classes = [VisitThrottle,]
def get(self, request, *args, **kwargs): ret = {'code': 1000, 'msg': None, 'data': None}
try:
ret['data'] = ORDER_DICT
except Exception as e:
pass
return JsonResponse(ret)

  

全局配置:

"DEFAULT_THROTTLE_CLASSES": ["api.utils.throttle.UserThrottle"],
"DEFAULT_THROTTLE_RATES": {
"keyword": '3/m', #限制1分钟内访问3次
"keyword2": '10/m', #限制1分钟内访问10次
},

  

第二版:

from rest_framework.throttle import SimpleRateThrottle

class VisitThrottle(SimpleRateThrottle):
scope = "keyword" def get_cache_key(self, request, view):
return self.get_ident(request) class UserThrottle(SimpleRateThrottle):
scope = "keyword2" def get_cache_key(self, request, view):
return request.user.username
#scope 传递参数给 settings里面的做限制参数使用
"DEFAULT_THROTTLE_RATES": {
"keyword": '3/m', #限制1分钟内访问3次
"keyword2": '10/m', #限制1分钟内访问10次
},

  

第一版:

- 必须继承 BaseThrottle

- 必须实现 allow_request 和wait 方法

第二版:

- 必须继承 SimpleRateThrottle

- 必须实现 get_cache_key方法 传递参数 scope = “userkey”

- 在settings中 写入限制参数  "userkey": '10/m', #限制1分钟内访问10次

最新文章

  1. cassandra-replication_factor 和 consistency level
  2. &lt;转&gt;ORA-06413 连接未打开错误
  3. HTML Entity Sets - All
  4. LeetCode Implement pow(x, n).
  5. PHP类与面向对象(二)
  6. Python输入和输出
  7. hadoop2.1.0和hadoop2.2.0编译安装教程
  8. __bridge,__bridge_transfer和__bridge_retained的使用和区别【转载】
  9. 【java学习笔记】文件操作
  10. note 7 递归函数
  11. nginx介绍(三) 配置篇
  12. js4
  13. BZOJ.3631.[JLOI2014]松鼠的新家(树上差分)
  14. MySQL Workbench在archlinux中出现 Could not store password: The name org.freedesktop.secrets was not provided by any .service files的错误
  15. C++句柄解析
  16. gradle-4.1-all.zip离线包下载 极速 android studio2.3 3.0编译必备
  17. Java获取文件后缀名
  18. 两个listbox 复制
  19. javac编译单文件、多文件引入jar包、-cp解决无法加载主类问题
  20. C/C++-中的sort排序用法

热门文章

  1. JNI调用C和C++存在的区别
  2. DataFactory生产身份证号码==
  3. linux的最简socket编程
  4. 关于OpenCL中三重循环的执行次序
  5. oracle相关知识点
  6. git服务器搭建---便签做备注
  7. MySQL 判断数据库和数据表是否存在
  8. node-sass 安装失败解决方案
  9. Oracle GoldenGate OGG管理员手册
  10. Flutter 底部导航栏bottomNavigationBar