面试题答案
一键面试实现思路
- 识别用户组:在中间件中获取当前请求的用户信息,判断用户所属的用户组。
- 定义限流规则:为不同用户组设定不同的限流规则,例如限制每分钟、每小时的请求次数。
- 记录请求:使用缓存(如 Django 内置的缓存机制)来记录每个用户的请求次数。
- 检查限流:每次请求到达时,检查该用户是否超过了其所属用户组的限流规则,若超过则返回相应的错误响应。
关键代码片段
from django.http import HttpResponse
from django.core.cache import cache
from django.contrib.auth.models import Group
class ThrottleMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if request.user.is_authenticated:
user_groups = request.user.groups.all()
throttle_rules = {
'group1': {'limit': 10, 'period': 60}, # 组1:每分钟10次请求
'group2': {'limit': 50, 'period': 3600} # 组2:每小时50次请求
}
for group in user_groups:
if group.name in throttle_rules:
rule = throttle_rules[group.name]
cache_key = f'throttle_{request.user.id}_{group.name}'
current_count = cache.get(cache_key, 0)
if current_count >= rule['limit']:
return HttpResponse('请求频率过高,请稍后再试', status=429)
cache.set(cache_key, current_count + 1, rule['period'])
response = self.get_response(request)
return response
在 settings.py
中注册中间件:
MIDDLEWARE = [
...
'path.to.ThrottleMiddleware',
...
]