【问题标题】:Django REST Throttling with Redis使用 Redis 进行 Django REST 节流
【发布时间】:2020-12-18 18:11:43
【问题描述】:

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

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

我已经在base.py中添加了我的Redis缓存,如下sn-p所示:

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'

我知道在这种情况下我必须覆盖throttle_success,但我不确定要确切更改什么。 帮助?! 谢谢。

【问题讨论】:

    标签: django caching django-rest-framework redis throttling


    【解决方案1】:

    你的配置有问题,你的设置也应该有默认缓存。

    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",
            "LOCATION": "redis://127.0.0.1:6379",
            "OPTIONS": {
                "DB": 2,
                "CLIENT_CLASS": "redis_cache.client.DefaultClient",
            }
        }
    }
    

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

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

    【讨论】:

    • 非常感谢。会试一试
    猜你喜欢
    • 1970-01-01
    • 2014-03-22
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 2017-10-21
    • 2021-08-29
    相关资源
    最近更新 更多