MST
星途 面试题库

面试题:Python Django中间件在处理复杂业务场景中的应用

假设在一个Django项目中,需要对特定用户请求进行限流,且不同用户组有不同的限流规则,使用中间件来实现这个功能,阐述实现思路并给出关键代码片段。
14.5万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 识别用户组:在中间件中获取当前请求的用户信息,判断用户所属的用户组。
  2. 定义限流规则:为不同用户组设定不同的限流规则,例如限制每分钟、每小时的请求次数。
  3. 记录请求:使用缓存(如 Django 内置的缓存机制)来记录每个用户的请求次数。
  4. 检查限流:每次请求到达时,检查该用户是否超过了其所属用户组的限流规则,若超过则返回相应的错误响应。

关键代码片段

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',
   ...
]