python (django) 4. 限流 throttle

1. api/throttle.py

# -*- coding: utf8 -*-

from rest_framework.throttling import SimpleRateThrottle


class AnonymousThrottle(SimpleRateThrottle):
    scope = 'anonymous'

    def get_cache_key(self, request, view):
        print(self.get_ident(request))
        return self.get_ident(request)


class StudentThrottle(SimpleRateThrottle):

    scope = 'student'

    def get_cache_key(self, request, view):
        print(request.user.name)
        return request.user.name

2. settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES':  ['api.authenticate.StudentAuthenticate'],
    'DEFAULT_PERMISSOIN_CLASSES': ['api.permission.GradeOnePermisson'],
    'UNAUTHENTICATED_USER': None,  # request.user
    'UNAUTHENTICATED_TOKEN': None,  # request.auth
    'DEFAULT_THROTTLE_CLASSES': ['api.throttle.StudentThrottle', 'api.throttle.AnonymousThrottle'],
    'DEFAULT_THROTTLE_RATES': {
        'anonymous': '2/m',
        'student': '5/m',
    }
}

3. api/views.py

class TokenView(GenericViewSet):

    # authentication_classes = []
    # permission_classes = [GradeOnePermission]
    parser_classes = [JSONParser, ]
    # throttle_classes = []

    def get(self, request, *args, **kwargs):
        name = request.query_params.get('name')
        try:
            stu = Student.objects.get(name=name)
        except Student.DoesNotExist:
            raise ParseError(_('Student does not include this name'))

        token = stu.token.token
        res = dict()
        res['code'] = 200
        res['name'] = name
        res['token'] = token
        logger.info(pformat(res))

        return Response(data=res, status=status.HTTP_200_OK)

4. postman

(1) http://127.0.0.1:8011/api/v1/token/?name=student1&token=dbfa6b230b9ca22302a00ea918346f86

(2)http://127.0.0.1:8011/api/v1/token/?name=student1&token=dbfa6b230b9ca22302a00ea918346f86

(3)http://127.0.0.1:8011/api/v1/token/?name=student1&token=dbfa6b230b9ca22302a00ea918346f86

return:

{
    "detail": "Request was throttled. Expected available in 55 seconds."
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值