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)
归档时间: |
|
查看次数: |
19191 次 |
最近记录: |