Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

python - How to cache Django Rest Framework API calls?

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

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

I'm about to try DRF-extensions which provide caching functionality:

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

but the build status on github is currently saying "build failing".

My app is very read-heavy on api calls. Is there a way to cache these calls?

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ok, so, in order to use caching for your queryset:

class ProductListAPIView(generics.ListAPIView):
    def get_queryset(self):
        return get_myobj()
    serializer_class = ProductSerializer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...