快速入手-基于Django-rest-framework的限流操作(十二)

        限流:对接口访问的频次进行限制,以减轻服务器压力或者实现特定的业务。一般用于付费购买次数、投票等场景使用。

        配置方式有两种:全局配置和局部配置。

1、全局配置

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework_simplejwt.authentication.JWTAuthentication",
    ),
    "DEFAULT_THROTTLE_CLASSES": [
        "rest_framework.throttling.AnonRateThrottle",  # 未认证用户
        "rest_framework.throttling.UserRateThrottle",  # 已认证用户
    ],
    "DEFAULT_THROTTLE_RATES": {  # 频率配置
        "anon": "2/min",  # 匿名用户每分钟最多访问 2 次
        "user": "10/min",  # 认证用户每分钟最多访问 10 次
    },

}

2、测试

2、局部配置

REST_FRAMEWORK = {

    "DEFAULT_AUTHENTICATION_CLASSES": (

        "rest_framework_simplejwt.authentication.JWTAuthentication",

    ),

    # "DEFAULT_THROTTLE_CLASSES": [

    #     "rest_framework.throttling.AnonRateThrottle",  # 未认证用户

    #     "rest_framework.throttling.UserRateThrottle",  # 已认证用户

    # ],

    "DEFAULT_THROTTLE_RATES": {  # 频率配置

        "anon": "2/min",  # 匿名用户每分钟最多访问 2 次

        "user": "5/min",  # 认证用户每分钟最多访问 10 次

    },

}

3、视图类里views.py配置

from django.shortcuts import render, HttpResponse

from rest_framework.response import Response

from rest_framework.decorators import action

from rest_framework.viewsets import GenericViewSet

from rest_framework.mixins import (

    ListModelMixin,

    CreateModelMixin,

    RetrieveModelMixin,

    UpdateModelMixin,

    DestroyModelMixin,

)

from rest_framework.viewsets import ModelViewSet

from rest_framework import serializers

from rest_framework.authentication import (

    BasicAuthentication,

    SessionAuthentication,

)

from rest_framework.permissions import (

    IsAuthenticated,

    AllowAny,

    IsAuthenticatedOrReadOnly,

)


 

from .models import *

from api.serializer import *

from rest_framework.throttling import UserRateThrottle


 

# 这种写法实现所有的增删改查,不能够单独进行操作

# class Linkapi(ModelViewSet):

# 不仅可以实现所有的增删改查,而且可以单独也可以全部包含增删改查

class Linkapi(

    GenericViewSet,

    ListModelMixin,

    CreateModelMixin,

    RetrieveModelMixin,

    UpdateModelMixin,

    DestroyModelMixin,

):

    queryset = Link.objects.all()

    serializer_class = LinkSerializer

    # authentication_classes = [SessionAuthentication]

    # IsAuthenticated 授权登录后可以访问

    # IsAuthenticatedOrReadOnly  只允许查询

    permission_classes = [IsAuthenticatedOrReadOnly]

    # 限流局部配置

    throttle_classes = [UserRateThrottle]

4、用户也可以自定义限流,这个用AI去找demo即可。

5、代码下载

链接: https://pan.baidu.com/s/15Sro9DZHMDdPtYaJ7418mQ?pwd=gfwn 提取码: gfwn

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神奇侠2024

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值