微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Redis进行Django REST节流

如何解决使用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']

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。