簡體   English   中英

如何使用 django rest 框架為不同的用戶設置不同的節流范圍?

[英]How to set different throttle scopes for different users using django rest framework?

例如:為客戶和員工設置不同的節流率。 這可以使用UserRateThrottle來完成嗎? 例如:

REST_FRAMEWORK['DEFAULT_THROTTLE_CLASSES'] = ('backend.throttles.EmployeeThrottle')
REST_FRAMEWORK['DEFAULT_THROTTLE_RATES'] = {
    'user': config.THROTTLE_RATE,
    'employee': config.EMPLOYEE_THROTTLE_RATE
}

from rest_framework.throttling import UserRateThrottle

class EmployeeThrottle(UserRateThrottle):
    *WHAT TO DO HERE?*

我可以在這個EmployeeThrottle類中以某種方式獲取請求並根據該請求內容設置范圍。

編輯:例如: UserRateThrottle這里BurstRateThrottle ,如果不知何故,我能得到我的請求可以設置基於該范圍。

如果這是每個用戶類型,那么您應該使用BaseThrottle作為基類。 我認為這樣的事情應該有效嗎?

class UserRateThrottle(throttling.BaseThrottle):
    scope = 'user'
    def allow_request(self, request, view):
        return request.user.type == 'user'


class EmployeeRateThrottle(throttling.BaseThrottle):
    scope = 'employee'
    def allow_request(self, request, view):
        return request.user.type == 'employee'
from rest_framework.throttling import UserRateThrottle


class CustomThrottle(UserRateThrottle):
    def __init__(self):
        pass
    def allow_request(self, request, view):
        employee_scope = getattr(view, 'employee', None)
        user_scope = getattr(view, 'user', None)
        if request.user.profile.is_employee:
            if not employee_scope:
                return True
            self.scope = employee_scope
        else:
            if not user_scope:
                return True
            self.scope = user_scope 
            
        self.rate = self.get_rate()
        self.num_requests, self.duration = self.parse_rate(self.rate)
        
        return super().allow_request(request, view)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM