访问记录 = {
身份证号: [ :: ,::, ::]
}
#:: ,::,:: ,::, #::
#[::, ::, ::] #访问记录 = {
用户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. HDU - 4758 Walk Through Squares (AC自己主动机+DP)

    Description   On the beaming day of 60th anniversary of NJUST, as a military college which was Secon ...

  2. IIS身份验证的配置

    前4者配置:localhost applicationHost.config <location path=""> 后2者配置:web.config 要点: 这6项尽管 ...

  3. (三 )kafka-jstorm集群实时日志分析 之 ---------jstorm集成spring 续(代码)

    本地模式启动的. package com.doctor.kafkajstrom; import java.util.HashMap; import java.util.Map; import java ...

  4. 【BUG】android.content.res.Resources$NotFoundException: File res/drawable-xxhdpi/toolbar_line.png from

    SafeGod在coolpad(4.0)上执行.登陆进去的设备列表界面遇到的问题.三星和索尼没有这个问题. 06-24 15:23:06.897: E/AndroidRuntime(12655): F ...

  5. rails数据库操作rake db一点心得

    问题描述,对于很多的新手rails lover来说,搞定db是件头疼的事情,当建立了一个model,测试了半天发现我草列名写错了,再过一会儿发现association里面竟然没有xxx_id,这下子s ...

  6. [Avito Code Challenge 2018 G] Magic multisets(线段树)

    题目链接:http://codeforces.com/contest/981/problem/G 题目大意: 有n个初始为空的‘魔法’可重集,向一个‘可重集’加入元素时,若该元素未出现过,则将其加入: ...

  7. 时域,频域,s域和z域,一些网上的总结

    https://www.jianshu.com/p/29f4a7663b14 https://wenku.baidu.com/view/26961183b9d528ea81c779e0.html ht ...

  8. Ubuntu 14.04下安装CUDA8.0

    配置环境如下: 系统:Ubuntu14.04 64bit 显卡:Nvidia K620M 显卡驱动:Nvidia-Linux-x86_64-375.66.run CUDA8.0 +  cudnn8.0 ...

  9. 使用rman恢复数据小结

    恢复前提有数据备份 以 alter database open resetlogs 开机以后多要做一次全备(以前的备份失效了) 恢复参数文件: restore spfile from '/home/o ...

  10. mongodb报错:connection refused because too many open connections: 819

    问题: 发现mongodb无法连接,查看mongodb日志,出现大量的如下报错: [initandlisten] connection refused because too many open co ...