如何缓存 Django Rest Framework API 调用? [英] How to cache Django Rest Framework API calls?

查看:34
本文介绍了如何缓存 Django Rest Framework API 调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 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)

如果你想缓存整个视图:

If you want to cache the whole view:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆