如何使用持久缓存缓存DJANGO REST框架(检索)

发布于 2025-02-06 12:43:25 字数 1219 浏览 3 评论 0 原文

我有以下DJANGO REST视图:

class AnnotationViewSet(
        mixins.CreateModelMixin,
        mixins.ListModelMixin,
        mixins.RetrieveModelMixin,
        viewsets.GenericViewSet
    ):
    queryset = Annotation.objects.all()
    serializer_class = AnnotationSerializer

访问单个方法将通过 Mixins.RetRieveModelMixin 来调用检索函数。我想加快函数,因为它需要多个查询,并且使用了很多CPU。
特别是:

  • 我希望
  • 根据检索到的记录重新启动应用程序后可以使用的持久缓存需要不同(例如=“ nofollow noreferrer”> http://127.0.0.0.1/annotations/1 VS 等)

到目前为止,我尝试覆盖视图检索方法:

    @method_decorator(cache_page(60 * 60 * 24 * 365))
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

并将默认的缓存设置为磁盘:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': '/home/django_cache',
    }
}

我认为它不起作用,因为我需要缓存约200万个项目(我有大约200万记录):文件夹/home/django_cache 使用少于MB,并且每次调用API时的尺寸会更改。

I have the following Django REST view:

class AnnotationViewSet(
        mixins.CreateModelMixin,
        mixins.ListModelMixin,
        mixins.RetrieveModelMixin,
        viewsets.GenericViewSet
    ):
    queryset = Annotation.objects.all()
    serializer_class = AnnotationSerializer

Accessing a single method will call the retrieve function thanks to mixins.RetrieveModelMixin. I would like to speed up the function since it requires multiple queries and it uses a lot of CPU.
In particular:

As of now I tried to overwrite the view retrieve method:

    @method_decorator(cache_page(60 * 60 * 24 * 365))
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

and to set the default cache to disk:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': '/home/django_cache',
    }
}

I don't think it is working, as I need to cache about 2 million items (I have about 2 millions records): the folder /home/django_cache uses less than a Mb and it's size changes every time I call the API.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文