【问题标题】:Django Rest Framework: not showing latest records unless i restart the serverDjango Rest Framework:除非我重新启动服务器,否则不显示最新记录
【发布时间】:2020-09-05 19:48:54
【问题描述】:

我正在使用 django rest 框架来创建和检索记录,但我注意到当我创建新记录然后尝试获取记录列表时,即使在 24 小时后它也不会显示在记录列表中,除非我重新启动 gunicorn 服务器。

我认为这与缓存有关,但我在有关缓存的文档中没有发现任何有趣的内容。

我想保留缓存,因为它对性能有好处...但我希望显示新记录,添加记录后是否有刷新缓存?或类似的东西?

【问题讨论】:

  • 除非您发布一些代码,否则我们无法为您提供帮助,原因之一可能是您正在为查询集使用模块/类级别属性,只有在您重新启动代码时才会重新加载。
  • @JamesLin 是的,你是对的,我已经解决了,谢谢!

标签: django caching django-rest-framework


【解决方案1】:

您可以在视图的 get 或 list 方法中使用 method_decorator 和 cache_page

首先你必须导入它

from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page

例子:

class CLASSNAME(APIView):

    # Cache page for the requested url
    @method_decorator(cache_page(60*60*2))  # 2 hour
    def get(self, request, format=None):

        """ Your codes """

class CLASSNAME(viewsets.ViewSet):

    # Cache requested url for each user for 2 hours
    @method_decorator(cache_page(60*60*2))
    def list(self, request, format=None):
        """ Your codes """

希望对你有帮助

【讨论】:

  • 我在文档中看到了这个,这设置了每个视图的缓存,但它没有修复丢失的记录。
猜你喜欢
  • 2015-03-09
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
  • 1970-01-01
  • 2022-11-09
  • 1970-01-01
  • 2020-08-24
相关资源
最近更新 更多