如何使用Django Rest Framework实现Redis缓存? [英] How to implement Redis Cache with Django Rest Framework?
问题描述
我需要在Django Rest Framework网站上实现Redis缓存。但是
当我使用带有类的cache_page装饰器进行负载测试时,每秒可以提高请求,但会出现错误函数对象没有属性'get_extra_actions'。
I need to implement Redis cache with my Django Rest Framework site. But when I do load test using cache_page decorator with a class it improves the request per second but an error occurs "'function' object has no attribute 'get_extra_actions'"
Views.py
@cache_page(CACHE_TTL)
class ParameterViewSet(viewsets.ModelViewSet):
"""
Lists all the parameters present in the system.
Can pass filter with parent set to null to get top level
Parameters.
"""
permission_classes = (IsAuthenticated,)
queryset = Parameter.objects.all()
filter_fields = ('parent', 'target_type',)
serializers = {
'default': ParameterSerializer,
'list': ParameterSerializer,
'detail': ParameterSerializer,
'update': ParameterWriteSerializer,
'create': ParameterWriteSerializer,
'delete': ParameterWriteSerializer,
}
def get_serializer_class(self):
return self.serializers.get(
self.action,
self.serializers['default'])
def get_queryset(self):
results = Parameter.objects.all().filter(weight__gt=0).order_by(
'order_number')
if 'no_parent' in self.request.query_params:
return results.filter(parent=None)
return results
在我的Settings.py中,我还添加了以下代码。
In my Settings.py, I have also added the below code.
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379/',
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
}
}
}
我也相应地添加了以下中间件
also i have add the below middleware accordingly
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddleware',
# place all other middlewares here
'django.middleware.cache.FetchFromCacheMiddleware',
]
那也行不通。
推荐答案
从我的头顶开始,您就在使用 @cache_page(CACHE_TTL)
在错误的位置以错误的方式。
Just from top of my head you are using the @cache_page(CACHE_TTL)
at the wrong place and in the wrong way.
根据django docs',您需要 cache_page
装饰器位于类的方法之上,而不是类本身,并且需要包装在 method_decorator
中。
According to django docs' you need the cache_page
decorator to be above class' method not the class itself and it need to be wrapped in method_decorator
.
如下所示覆盖 ParameterViewSet
的调度
,它应该可以完成工作。 / p>
Overwrite ParameterViewSet
's dispatch
like below and it should do the job.
@method_decorator(cache_page(CACHE_TTL))
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
文档:
- Decorating the class
- Using cache with apiview and viewsets
这篇关于如何使用Django Rest Framework实现Redis缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!