Django REST框架Redis限流报错:'dict'对象无'set'属性求助
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 usesredis_cache.cache.RedisCache, make sure you've installed the required package:pip install django-redis-cacheVerify Throttle Rate Configuration
Double-check that yourbase.pyhas the rate defined for yourcustom_throttlescope: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 atredis://127.0.0.1:6379and that the database (DB 1) is accessible.
内容的提问来源于stack exchange,提问作者Omar Gaber Abdelmaksoud

