import time
import json
import redis
from django.http import JsonResponse
from django.conf import settings

rd_pool = settings.REDIS_POOL_THROTTLE


def throttle_request(rate_limit=10, period=60):
    """
    接口限流解释器，通过REMOTE_ADDR对view接口进行访问限制
    :param rate_limit 单位时间内最大访问次数
    :param period 单位时间大小，计量单位秒
    """
    def decorator(view_func):
        def wrapped_view(request, *args, **kwargs):
            # 使用用户的 IP 地址作为唯一标识符
            ip_address = request.META.get('REMOTE_ADDR')

            # 构建缓存键
            cache_key = f'throttle_{ip_address}_{request.path}'
            # 使用连接池创建Redis客户端
            rd = redis.StrictRedis(connection_pool=rd_pool)

            # 获取上次访问时间和访问次数
            access_info = rd.get(cache_key)
            if access_info is None:
                access_info = {'last_request_time': time.time(), 'request_count': 1}
                rd.set(cache_key, json.dumps(access_info), ex=period)
            else:
                access_info = json.loads(access_info)
                current_time = time.time()
                if current_time - float(access_info['last_request_time']) > period:
                    access_info['last_request_time'] = current_time
                    access_info['request_count'] = 1
                    rd.set(cache_key, json.dumps(access_info), ex=period)
                else:
                    access_info['request_count'] += 1
                    if access_info['request_count'] > rate_limit:
                        return JsonResponse({'error': '请求频率过高，请稍后再试！'}, status=403)
                    else:
                        rd.set(cache_key, json.dumps(access_info), ex=period)

            # 调用视图函数
            return view_func(request, *args, **kwargs)
        return wrapped_view
    return decorator
