访问记录 = {
身份证号: [ :: ,::, ::]
}
#:: ,::,:: ,::, #::
#[::, ::, ::] #访问记录 = {
用户IP: [...]
} import time
VISIT_RECORD = {} #存放IP的数据库 可以放在缓存! from rest_framework.thrittling import BaseThrottle
class VisitThrattle(object):
def __init__(self):
self.history = None def allow_request(self, request, view):
"""
写一些业务逻辑
获取用户IP地址
60s内只能访问3次
"""
remote_addr = request._request.META.get('REMOTE_ADDR')
print(remote_addr) #访问记录IP
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[[-] < ctime -:
history.pop() if len(history) < :
history.insert(, ctime)
return True
return False return True #判断是否可以继续访问 True可以访问 频率没有达到最大
#return False如果返回False频率太高,已经被限制 无法继续下一步访问 def wait(self):
#显示还需要等多少秒
ctime = time.time() return = - (ctime - self.history[-]) class AuthView(APIView):
authentication_calsses = []
permission_classes = []
throttle_classes = [VisitThrattle,]
def post(self, request, *args, **kwargs):
#去 request获取IP
#访问记录 全局配置的话
REST_FRAMEWORK = {
"DEFAULT_THROTTLE_CLASSES" : ['api.utlis.throttle.VisitThrottle']
} 内置控制频率的类:
BaseThrottle SimpleRateThrottle(BaseThrottle) allow_request
from rest_framework.throttling import BaseThrottle, SimpleRateThrottle
class VisitThrottle(SimpleRateThrottle): #对匿名用户的ip号通过时间做访问频率控制
scope = 'Luffy' #指定setting配置文件中Luffy(key) def get_cache_key(self, request, view): #去缓存里取数据
return self.get_ident(request) class UserThrottle(SimpleRateThrottle): #对用户的名字 通过时间做访问频率控制
scope = "LuffyUser" def get_cache_key(self, request, view):
return request.user.username 然后再views.py添加
from api.utils.throttle import UserThrottle
在创建的函数里添加
throttle_classes = ["UserThrottle"] 在setting.py加
REST_FRAMEWORK = {
"DEFAULT_THROTTLE_CLASSES":['api.utils.throttle.VisitThrottle'],
"DEFAULT_THROTTLE_RATES":{
"Luffy":'3/m' #每分钟访问3次 #duration = {'s':, 'm':, 'h':, 'd':}[period[]]
"LuffyUser": /m
}
} 梳理:
a. 基本使用
-类, 继承BaseThrottle 实现 allow_request wait 两个方法 加个__init__构造函数
-类, 继承SimpleRateThrottle 实现 get_cache_key scope = "Luffy" (配置文件中的key) b. 局部使用
class AuthView(APIView):
throttle_classes = [ VisitThrottle, ] #>>>>>> 全局
REST_FRAMEWORK = {
"DEFAULT_THROTTLE_CLASSES":['api.utils.throttle.VisitThrottle'],
"DEFAULT_THROTTLE_RATES":{
"Luffy":'3/m' #每分钟访问3次 #duration = {'s':, 'm':, 'h':, 'd':}[period[]]
"LuffyUser": /m
}
}

rest_framework 节流功能(访问频率)的更多相关文章

  1. rest_framework 访问频率(节流)流程

    访问频率流程 访问频率流程与认证流程非常相似,只是后续操作稍有不同 当用发出请求时 首先执行dispatch函数,当执行当第二部时: #2.处理版本信息 处理认证信息 处理权限信息 对用户的访问频率进 ...

  2. rest_framework组件之认证,权限,访问频率

    共用的models from django.db import models # Create your models here. class User(models.Model): username ...

  3. RestFramework自定制之认证和权限、限制访问频率

    认证和权限 所谓认证就是检测用户登陆与否,通常与权限对应使用.网站中都是通过用户登录后由该用户相应的角色认证以给予对应的权限. 权限是对用户对网站进行操作的限制,只有在拥有相应权限时才可对网站中某个功 ...

  4. Django REST framework 自定义(认证、权限、访问频率)组件

    本篇随笔在 "Django REST framework 初识" 基础上扩展 一.认证组件 # models.py class Account(models.Model): &qu ...

  5. 从FBV到CBV四(访问频率限制)

    比如我们有一个用户大转盘抽奖的功能,需要规定用户在一个小时内只能抽奖3次,那此时对接口的访问频率限制就显得尤为重要 其实在restframework中已经为我们提供了频率限制的组件 先捋一下请求到AP ...

  6. DRF框架之 用户角色权限与访问频率的权限设置

    1. 简单演示,创建一个models的数据库表 class User(models.Model): name=models.CharField(max_length=32) pwd=models.Ch ...

  7. cache 访问频率的思考

    互联网的项目用户基数很大,有时候瞬间并发量非常大,这个时候对于数据访问来说是个灾难.为了应对这种场景,一般都会大量采用web服务器集群,缓存集群.采用集群后基本上就能解决大量并发的数据访问.当然这个时 ...

  8. django Rest Framework----认证/访问权限控制/访问频率限制 执行流程 Authentication/Permissions/Throttling 源码分析

    url: url(r'books/$',views.BookView.as_view({'get':'list','post':'create'})) 为例 当django启动的时候,会调用执行vie ...

  9. Redis 实现接口访问频率限制

    为什么限制访问频率 做服务接口时通常需要用到请求频率限制 Rate limiting,例如限制一个用户1分钟内最多可以范围100次 主要用来保证服务性能和保护数据安全 因为如果不进行限制,服务调用者可 ...

随机推荐

  1. POJ 2369

    我们知道,当循环长度为L时,置换群幂次为K ,则结果是GCD(L,K)个积相乘. 于是,我们只需要求出每个循环的长度,求得它们的最小公倍数即为解. #include <iostream> ...

  2. ZOJ 3687

    赤裸的带禁区的排列数,不过,难点在于如何用程序来写这个公式了.纠结了好久没想到,看了看别人的博客,用了DFS,实在妙极,比自己最初想用枚举的笨方法高明许多啊.\ http://blog.csdn.ne ...

  3. poj2965 The Pilots Brothers&#39; refrigerator(直接计算或枚举Enum+dfs)

    转载请注明出处:http://blog.csdn.net/u012860063? viewmode=contents 题目链接:http://poj.org/problem? id=2965 ---- ...

  4. CF 567C(Geometric Progression-map)

    C. Geometric Progression time limit per test 1 second memory limit per test 256 megabytes input stan ...

  5. LeetCode OJ 215. Kth Largest Element in an Array 堆排序求解

    题目链接:https://leetcode.com/problems/kth-largest-element-in-an-array/ 215. Kth Largest Element in an A ...

  6. app-framework学习--nav的Scroller禁用与启用

    app-framewor(jqmobi) nav的Scroller禁用与启用 写在panel 的 data-load 方法里 禁用  $.ui.scrollingDivs.menu_scroller. ...

  7. JAVA设计模式之【命令模式】

    命令模式 为了降低耦合度,将请求的发送者和接收者解耦 发送请求的对象只需要哦知道如何发送请求,而不必知道如何完成请求 对请求排队 记录请求日志 支持撤销操作 核心在于引入命令类 角色 抽象命令类Com ...

  8. pip更新问题

    pip更新及Requirement already up-to-date解决方法 pip更新 更新命令 将pip更新版本 1 python -m pip install --upgrade pip R ...

  9. 2019Pycharm激活方法

    1.将“0.0.0.0 account.jetbrains.com”添加到hosts文件中 2.打开http://idea.lanyus.com/ 3.获取激活码,粘贴到第二个选项中 亲测可用.

  10. POJ 1195 Mobile phones【 二维树状数组 】

    题意:基础的二维数组,注意 0 + lowbit(0)会陷入无限循环----- 之前做一道一维的一直tle,就是因为这个-------------------------- #include<i ...