自定义频率限制

频率限制

源码略:

需要的时候再研究

自定义频率限制组件:

思路:

利用源码存在的东西然后自己自定义类,进行关键处修改

1 settings.py

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_RATES': {
        'user': '5/min', # 系统再带对用户的限制,在自定义里面并没有启用 (结合源码启用)
        'anon': '3/min', # 系统自带对游客的限制,在自定义里面并没有启用(结合源码启用)
        'count_time': '3/min'
    }
}

2 新建api/throttles.py

# ps 缓存默认用的django缓存(在源码中有个会设置 self.cach)
from rest_framework.throttling import SimpleRateThrottle

class ThreeMinRateThrottle(SimpleRateThrottle):
    scope = 'count_time' # 这个要在drf的settings里配置好限制的频率
    def get_cache_key(self, request, view):
        # 就是限制的标识:用户id、IP地址、手机号
        ident = request.user.pk
        return self.cache_format % {
            'scope': self.scope,
            'ident': ident
        }

3 views.py

from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAdminUser
from .permissions import AdminPermission
from rest_framework.throttling import AnonRateThrottle, UserRateThrottle
from .throttles import  ThreeMinRateThrottle
class UserListAPIView(ListAPIView):
    queryset = models.User.objects.filter(is_active=True)
    serializer_class = serializers.UserModelSerializer
    # 登录的用户必须是自定义管理员分组成员
    permission_classes = [AdminPermission]
    # 频率限制
    throttle_classes = [ThreeMinRateThrottle]
    # drf自带频率限制组件,没试过。
    # throttle_classes = [AnonRateThrottle, UserRateThrottle]

后台admin密码秘文

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin # 使得密码可以使用秘文

# Register your models here.
from . import models

admin.site.register(models.Car)
admin.site.register(models.User,UserAdmin)
posted @ 2019-12-02 16:57  张明岩  阅读(183)  评论(0编辑  收藏  举报