如何缓存Django Rest Framework API调用?

Kak*_*oin 24 python django memcached caching django-rest-framework

我正在使用Memcached作为我的django应用程序的后端.此代码在正常的django查询中工作正常:

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
Run Code Online (Sandbox Code Playgroud)

但是当与django-rest-framework api调用一起使用时它不起作用:

class ProductListAPIView(generics.ListAPIView):
    def get_queryset(self):
        product_list = Product.objects.all()
        return product_list
    serializer_class = ProductSerializer
Run Code Online (Sandbox Code Playgroud)

我即将尝试提供缓存功能的DRF扩展:

https://github.com/chibisov/drf-extensions

但是github上的构建状态目前正在说"构建失败".

我的应用程序在api调用时非常重读.有没有办法缓存这些电话?

谢谢.

Lin*_*via 39

好的,为了对您的查询集使用缓存:

class ProductListAPIView(generics.ListAPIView):
    def get_queryset(self):
        return get_myobj()
    serializer_class = ProductSerializer
Run Code Online (Sandbox Code Playgroud)

您可能希望在缓存集上设置超时(例如60秒):

cache.set(cache_key, result, 60)
Run Code Online (Sandbox Code Playgroud)

如果要缓存整个视图:

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)
Run Code Online (Sandbox Code Playgroud)

  • 当我完全如图所示尝试时,我得到一个错误`'ShopsList'对象没有属性'method'.有任何想法吗? (4认同)
  • 是@eugene,只需在URL路由器模式`cache_page(YourView.as_view())中调用视图上的cache_page. (2认同)
  • @Linovia 当产品更新或创建时,我们如何清除/刷新缓存? (2认同)