「Django」rest_framework学习系列-节流控制

本文深入探讨了Django REST framework中的限流机制,包括自定义限流类和内置限流类的应用。通过实例展示了如何设置访问频率,针对匿名用户和注册用户的不同限流策略,以及如何在settings中配置全局限流规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、节流自定义类:

import time
from api import models

VISIT_RECORD = {}

class VisitThrottle(BaseThrottle):
    #设置访问频率为60秒3次
    def allow_request(self, request, view):
        #获取用户ID
        # 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]
        history = VISIT_RECORD.get(remote_addr)
        self.history = history
        while history and history[-1] < ctime-60:
            history.pop()

        if len(history) < 3:
            history.insert(0,ctime)
            return True

    def wait(self):
        ctime = time.time()
        wtime = 60 - (ctime-self.history[-1])
        return wtime
View Code

2、内置节流类
a.项目下utils文件throttle.py文件:

from rest_framework.throttling import SimpleRateThrottle

#对匿名用户的限制
class VisitThrottle(SimpleRateThrottle):
    scope = 'none' #限制规则写在settings全局配置里
    def get_cache_key(self, request, view):
        return self.get_ident(request)

#对注册用户的限制
class UserThrottle(SimpleRateThrottle):
    scope = 'user'
    def get_cache_key(self, request, view):
        return request.user.username
View Code

b.settings配置用户全局认证如下:

'DEFAULT_THROTTLE_CLASSES':['api.utils.throttle.VisitThrottle',], #节流认证
'DEFAULT_THROTTLE_RATES':{
'none':'3/m',
'user':'10/m',
},

c.views业务类可以在全局认证外设置单独认证规则:

throttle_classes = []

 

转载于:https://www.cnblogs.com/wrxblog/p/10402559.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值