21 lines
944 B
Python
21 lines
944 B
Python
from rest_framework.throttling import SimpleRateThrottle
|
|
|
|
class ApiPathRateThrottle(SimpleRateThrottle):
|
|
scope = 'api_path'
|
|
|
|
def get_cache_key(self, request, view):
|
|
# 针对已认证的用户
|
|
if request.user.is_authenticated:
|
|
# 使用用户名作为限流的唯一标识符
|
|
return f"throttle_{self.scope}_{request.user.username}"
|
|
|
|
# 针对未认证的用户,使用 IP 地址作为唯一标识符
|
|
# 你可以使用 request.META['REMOTE_ADDR'] 来获取用户 IP 地址
|
|
return f"throttle_{self.scope}_{self.get_ident(request)}"
|
|
|
|
def allow_request(self, request, view):
|
|
# 检查请求路径是否以 '/api/ai/' 或者 '/api/ali/' 开头
|
|
if request.path.startswith('/api/ai/') or request.path.startswith('/api/ali/'):
|
|
return super().allow_request(request, view)
|
|
return True # 如果不是 /api/ 开头的请求,不进行限流
|