使用Redis进行Django REST节流

问题描述

我在多个线程中注意到,尤其是在生产环境中,我们需要使用更好的缓存(例如“ Redis”)代替Django的默认“ LocMemCache”。

我有多个设置文件,包括 base.pymaster.py

我已在base.py中添加了我的Redis缓存,如以下代码片段所示:

CACHES = {
    "alternate": {
        "BACKEND": "redis_cache.cache.RedisCache","LOCATION": "redis://127.0.0.1:6379","OPTIONS": {
            "DB": 1,"CLIENT_CLASS": "redis_cache.client.DefaultClient",}
    }
}

由于我不想在应用程序中更改缓存,因此我故意将其替换。

在我的自定义油门中,我没有以下实现:

from rest_framework.throttling import UserRateThrottle
from myproject.settings.base import CACHES

class CustomThrottle(UserRateThrottle):
    scope = 'custom_throttle'
    cache = CACHES['alternate']

在同一base.py文件中存在节流率

但是,当我向该端点运行请求时,遇到以下错误。

line 26,in throttle_success
    self.cache.set(self.key,self.history,self.duration)
AttributeError: 'dict' object has no attribute 'set'

我知道在这种情况下我必须重写节流阀成功,但是我不确定到底要更改什么。 救命?! 谢谢。

解决方法

您的配置存在问题,您的设置也应具有默认缓存。

CACHES = {
    "alternate": {
        "BACKEND": "redis_cache.cache.RedisCache","LOCATION": "redis://127.0.0.1:6379","OPTIONS": {
            "DB": 1,"CLIENT_CLASS": "redis_cache.client.DefaultClient",}
    },"default": {
        "BACKEND": "redis_cache.cache.RedisCache","OPTIONS": {
            "DB": 2,}
    }
}

一旦定义了这样的设置,就应该使用缓存对象而不是CACHE设置来更新CustomThrottle。

from django.core.cache import caches
class CustomThrottle(UserRateThrottle):
    scope = 'custom_throttle'
    cache = caches['alternate']

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...