rest_framework 访问频率(节流)流程
访问频率流程
访问频率流程与认证流程非常相似,只是后续操作稍有不同
当用发出请求时 首先执行dispatch函数,当执行当第二部时:
#2.处理版本信息 处理认证信息 处理权限信息 对用户的访问频率进行限制
self.initial(request, *args, **kwargs)
进入到initial方法:
def initial(self, request, *args, **kwargs):
"""
Runs anything that needs to occur prior to calling the method handler.
"""
self.format_kwarg = self.get_format_suffix(**kwargs) # Perform content negotiation and store the accepted info on the request
neg = self.perform_content_negotiation(request)
request.accepted_renderer, request.accepted_media_type = neg # Determine the API version, if versioning is in use.
#2.1处理版本信息
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme # Ensure that the incoming request is permitted
#2.2处理认证信息
self.perform_authentication(request)
#2.3处理权限信息
self.check_permissions(request)
#2.4对用户的访问频率进行限制
self.check_throttles(request)
#2.4对用户的访问频率进行限制
self.check_throttles(request)
下面 开始 限流的具体分析:
一、执行check_throttles方法
def check_throttles(self, request):
"""
Check if request should be throttled.
Raises an appropriate exception if the request is throttled.
"""
#遍历throttle对象列表
for throttle in self.get_throttles():
#根据allow_request()的返回值进行下一步操作,返回True的话不执行下面代码,标识不限流,返回False的话执行下面代码,还可以抛出异常
if not throttle.allow_request(request, self):
#返回False的话执行
self.throttled(request, throttle.wait())
局部访问频率
throttles.py
#局部访问频率
from rest_framework.throttling import BaseThrottle
import time
class VisitThorttles(object):
visit_thorttles={}
def __init__(self):
self.history=None def allow_request(self,request,view):
current_time=time.time()
# 访问用户的IP
visit_ip=request.META.get("REMOTE_ADDR")
# 第1 次访问时
if visit_ip not in self.visit_thorttles:
self.visit_thorttles[visit_ip]=[current_time] return True
self.history = self.visit_thorttles[visit_ip] # 第2、3次访问 默认单位时间只能访问3次,
if len(self.visit_thorttles[visit_ip])<3:
# 最新访问时间放在列表第一个
self.visit_thorttles[visit_ip].insert(0,current_time)
return True # # 判断当前时间与用户最早访问时间(列表对三个时间)的差值
if current_time-self.visit_thorttles[visit_ip][-1]>60:
self.visit_thorttles[visit_ip].pop()
self.visit_thorttles[visit_ip].insert(0,current_time)
return True return False
view.py
class BookViewsSet(viewsets.ModelViewSet):
# 访问频率
throttle_classes=[VisitThorttles]
queryset = Book.objects.all()
serializer_class = BookModelSerializer
全局访问频率
throttles.py
#局部访问频率
from rest_framework.throttling import BaseThrottle
import time
class VisitThorttles(object):
visit_thorttles={}
def __init__(self):
self.history=None def allow_request(self,request,view):
current_time=time.time()
# 访问用户的IP
visit_ip=request.META.get("REMOTE_ADDR")
# 第1 次访问时
if visit_ip not in self.visit_thorttles:
self.visit_thorttles[visit_ip]=[current_time] return True
self.history = self.visit_thorttles[visit_ip] # 第2、3次访问 默认单位时间只能访问3次,
if len(self.visit_thorttles[visit_ip])<3:
# 最新访问时间放在列表第一个
self.visit_thorttles[visit_ip].insert(0,current_time)
return True # # 判断当前时间与用户最早访问时间(列表对三个时间)的差值
if current_time-self.visit_thorttles[visit_ip][-1]>60:
self.visit_thorttles[visit_ip].pop()
self.visit_thorttles[visit_ip].insert(0,current_time)
return True return False
settings.py
REST_FRAMEWORK={
"DEFAULT_THROTTLE_CLASSES":["api.servise.throttles.VisitThorttles"],
}
内置访问频率
htorttles.py
# 内置的htorttles:
from rest_framework.throttling import SimpleRateThrottle class VisitThorttles(SimpleRateThrottle):
# 范围 visit_rate可自定义,与settings相匹配
scope = "visit_rate"
def get_cache_key(self, request, view): return self.get_ident(request)
settings.py
REST_FRAMEWORK = {
"DEFAULT_THROTTLE_RATES":{
'tiga':'10/m',
'anno':'5/m',
'user':'10/m',
'admin':'20/m',
}
}
待续
rest_framework 访问频率(节流)流程的更多相关文章
- rest_framework 节流功能(访问频率)
访问记录 = { 身份证号: [ :: ,::, ::] } #:: ,::,:: ,::, #:: #[::, ::, ::] #访问记录 = { 用户IP: [...] } import time ...
- django Rest Framework----认证/访问权限控制/访问频率限制 执行流程 Authentication/Permissions/Throttling 源码分析
url: url(r'books/$',views.BookView.as_view({'get':'list','post':'create'})) 为例 当django启动的时候,会调用执行vie ...
- rest_framework组件之认证,权限,访问频率
共用的models from django.db import models # Create your models here. class User(models.Model): username ...
- Django生命周期 URL ----> CBV 源码解析-------------- 及rest_framework APIView 源码流程解析
一.一个请求来到Django 的生命周期 FBV 不讨论 CBV: 请求被代理转发到uwsgi: 开始Django的流程: 首先经过中间件process_request (session等) 然后 ...
- RestFramework自定制之认证和权限、限制访问频率
认证和权限 所谓认证就是检测用户登陆与否,通常与权限对应使用.网站中都是通过用户登录后由该用户相应的角色认证以给予对应的权限. 权限是对用户对网站进行操作的限制,只有在拥有相应权限时才可对网站中某个功 ...
- rest_framework之频率详解 03
访问频率(节流) 1.某个用户一分钟之内访问的次数不能超过3次,超过3次则不能访问了,需要等待,过段时间才能再访问. 2.自定义访问频率.两个方法都必须写上. 登入页面的视图加上访问频率 3.返回值F ...
- 「Django」rest_framework学习系列-节流控制
1.节流自定义类: import time from api import models VISIT_RECORD = {} class VisitThrottle(BaseThrottle): #设 ...
- Django rest_framework 认证源码流程
一.请求到来后,都要先执行dispatch方法 dispatch根据请求方式的不同触发get/post/put/delete等方法 注意,APIView中的dispatch方法有很多的功能 def d ...
- Django Rest Framework用户访问频率限制
一. REST framework的请求生命周期 基于rest-framework的请求处理,与常规的url配置不同,通常一个django的url请求对应一个视图函数,在使用rest-framewor ...
随机推荐
- lintcode-45-最大子数组差
45-最大子数组差 给定一个整数数组,找出两个不重叠的子数组A和B,使两个子数组和的差的绝对值|SUM(A) - SUM(B)|最大. 返回这个最大的差值. 注意事项 子数组最少包含一个数 样例 给出 ...
- SSH Secure Shell Client的使用方法
1:双击其客户端图标,出现下图所示窗体 2:我使用她主要用于发布项目的,所以第一次使用会选择新建一个账户 3:填写账户的名称 4:完善账户的信息 5:主要用填下远程主机的IP/USER/PORT,在需 ...
- DES(Data Encryption Standard)数据加密标准
DES算法入口参数 DES算法的入口参数有三个:Key.Data.Mode.其中Key为7个字节共56位,是DES算法的工作密钥.Data为8个字节64位,是要被加密或解密的数据;Mode为DES的工 ...
- [LeetCode] 65. Valid Number(多个标志位)
[思路]该题题干不是很明确,只能根据用例来理解什么样的字符串才是符合题意的,本题关键在于几个标志位的设立,将字符串分为几个部分,代码如下: class Solution { public: strin ...
- BZOJ4481 JSOI2015非诚勿扰(概率期望+树状数组)
首先求出每个女性接受某个男性的概率.这个概率显然是一个无穷等比数列求和. 然后按编号从小到大考虑每个女性,维护出每个男性被选择的期望次数,BIT上查询后缀和即可. 需要long double. #in ...
- Codeforces Round #401 (Div. 1) C(set+树状数组)
题意: 给出一个序列,给出一个k,要求给出一个划分方案,使得连续区间内不同的数不超过k个,问划分的最少区间个数,输出时将k=1~n的答案都输出 比赛的时候想的有点偏,然后写了个nlog^2n的做法,T ...
- [Leetcode] Remove duplicates from sorted list 从已排序的链表中删除重复元素
Given a sorted linked list, delete all duplicates such that each element appear only once. For examp ...
- Codeforces 937.B Vile Grasshoppers
B. Vile Grasshoppers time limit per test 1 second memory limit per test 256 megabytes input standard ...
- 洛谷P1546 最短网络 Agri-Net
P1546 最短网络 Agri-Net 526通过 959提交 题目提供者JOHNKRAM 标签图论贪心USACO 难度普及/提高- 提交该题 讨论 题解 记录 最新讨论 50分C++代码,求解 请指 ...
- HDU3338:Kakuro Extension(最大流)
Kakuro Extension Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) ...