如何缓存Django Rest Framework API调用? [英] How to cache Django Rest Framework API calls?
问题描述
我正在使用Memcached作为django应用程序的后端.这段代码在普通的Django查询中可以正常工作:
I'm using Memcached as backend to my django app. This code works fine in normal django query:
def get_myobj():
cache_key = 'mykey'
result = cache.get(cache_key, None)
if not result:
result = Product.objects.all().filter(draft=False)
cache.set(cache_key, result)
return result
但是与django-rest-framework api调用一起使用时不起作用:
But it doesn't work when used with django-rest-framework api calls:
class ProductListAPIView(generics.ListAPIView):
def get_queryset(self):
product_list = Product.objects.all()
return product_list
serializer_class = ProductSerializer
我将尝试提供缓存功能的DRF扩展:
I'm about to try DRF-extensions which provide caching functionality:
https://github.com/chibisov/drf-extensions
,但是github上的构建状态当前表示构建失败".
but the build status on github is currently saying "build failing".
我的应用程序在api调用上非常繁重.有没有办法缓存这些呼叫?
My app is very read-heavy on api calls. Is there a way to cache these calls?
谢谢.
推荐答案
好,因此,为了对查询集使用缓存:
Ok, so, in order to use caching for your queryset:
class ProductListAPIView(generics.ListAPIView):
def get_queryset(self):
return get_myobj()
serializer_class = ProductSerializer
您可能想在缓存集上设置一个超时时间(例如60秒):
You'd probably want to set a timeout on the cache set though (like 60 seconds):
cache.set(cache_key, result, 60)
如果要缓存整个视图:
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
class ProductListAPIView(generics.ListAPIView):
serializer_class = ProductSerializer
@method_decorator(cache_page(60))
def dispatch(self, *args, **kwargs):
return super(ProductListAPIView, self).dispatch(*args, **kwargs)
这篇关于如何缓存Django Rest Framework API调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!