You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django REST框架Redis限流报错:'dict'对象无'set'属性求助

Fixing AttributeError in Custom Django Throttle with Redis Cache

Let's break down what's going wrong and how to fix it quickly:

Why the Error Happens

You assigned CACHES['alternate'] directly to self.cache in your CustomThrottle class—but CACHES['alternate'] is just a configuration dictionary, not an actual cache client instance. The dictionary doesn't have a set() method, which is why you're seeing that AttributeError.

Django requires you to use the initialized cache client (which wraps the Redis connection and provides methods like set(), get(), etc.) instead of the raw config dict.

The Fix: Use the Proper Cache Instance

Instead of referencing the config directly, use Django's caches utility to fetch the initialized cache client for your alternate Redis setup. Here's how to update your CustomThrottle class:

First, import the necessary modules:

from django.core.cache import caches
from rest_framework.throttling import UserRateThrottle

Then rewrite your throttle class:

class CustomThrottle(UserRateThrottle):
    scope = 'custom_throttle'

    def __init__(self):
        super().__init__()
        # Fetch the actual Redis cache instance instead of the config dict
        self.cache = caches['alternate']

That's it! The caches['alternate'] call returns the initialized Redis cache client with all the expected methods like set(), so your original throttle_success method will work without needing to rewrite it.

Additional Checks

  • Ensure Redis Cache Package is Installed
    Since your config uses redis_cache.cache.RedisCache, make sure you've installed the required package:

    pip install django-redis-cache
    
  • Verify Throttle Rate Configuration
    Double-check that your base.py has the rate defined for your custom_throttle scope:

    REST_FRAMEWORK = {
        'DEFAULT_THROTTLE_RATES': {
            'custom_throttle': '10/min'  # Adjust rate to your needs
        }
    }
    
  • Confirm Redis is Running
    Make sure your Redis server is up at redis://127.0.0.1:6379 and that the database (DB 1) is accessible.

内容的提问来源于stack exchange,提问作者Omar Gaber Abdelmaksoud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 23:53:16