在django rest框架中缓存响应的正确方法

aja*_*xon 5 caching django-rest-framework

我知道https://github.com/chibisov/drf-extensions但是构建失败了.

如何为通用视图缓存响应?例如:

class PropertyList(generics.ListAPIView):

    queryset = Property.objects.all().prefetch_related("photos")
    serializer_class = PropertyListSerializer


    filter_backends = (filters.DjangoFilterBackend,)
    filter_fields = ('featured', 'state', 'price_cents','location', 'status')
    ordering_fields = ('expiration_date',)
Run Code Online (Sandbox Code Playgroud)

从ListModelMixin实现list方法是唯一的选择吗?

Rez*_*adi 2

有一些解决方案:

  • 您可以将 APIview 和 ViewSets 的缓存与cache_page或之类的装饰器一起使用vary_on_cookie。像下面这样:

    class UserViewSet(viewsets.Viewset):
    
    # Cache requested url for each user for 2 hours
    @method_decorator(cache_page(60*60*2))
    @method_decorator(vary_on_cookie)
    def list(self, request, format=None):
        content = {
            'user_feed': request.user.get_user_feed()
        }
        return Response(content)
    
    Run Code Online (Sandbox Code Playgroud)

    在Django Rest 缓存原始页面中阅读更多相关信息

  • 您也可以按照自己的方式进行。我的意思是你可以只使用 django 中提供的缓存方法,例如cache.set. 例如,要仅存储方法或查询的结果并存储未来的请求,您可以为其定义一个键并将该结果设置为该键cache.set(cache_key, result, expire_time),然后在需要时获取它。因此,如果缓存可用于该键,则获取其他内容,然后再次从数据库获取结果并再次存储它。

    顺便说一句,它几乎与stackoverflow 上的此链接重复

请记住,您应该为结果定义一个缓存后端。默认情况下,您可以使用数据库后端在数据库或文件系统上存储带有键的结果。但正确且更好的解决方案是根据您的需求使用消息代理,例如 redis 或 memcached 或......。

这里还有一些其他有用的链接: