【问题标题】:Django: how to handle caching in views that differ for Ajax requests?Django:如何处理 Ajax 请求不同的视图中的缓存?
【发布时间】:2013-06-14 17:07:15
【问题描述】:

我有一个 Django 应用程序和一个 postgres 后端。它本质上是一个具有大型数据库的搜索站点,数据通常每天更改一次。我想开始缓存,以减少数据库的负载。

我已经设置了 memcached,但我的视图中有以下架构,旨在让我的应用在前端使用 Ajax:

@cache_page(60 * 60 * 12)
def items(request, pattern=None, specialurl=None):
  if request.is_ajax():
    template = "result_ajax.html"
  else: 
    template = "index.html"

.. 不幸的是,缓存加上对 Ajax 调用的特殊处理的组合效果不佳。

这是因为 memcached 不区分 Ajax 结果和非 Ajax 结果 - 因此来自前端的 Ajax 调用被给予缓存的非 Ajax 结果,反之亦然。

所以我需要做的是弄清楚如何缓存。我可以想到以下选项:

  1. 仅缓存数据库查询,一次最多缓存一天。这可能吗?
  2. 在result_ajax.html 中缓存实际显示结果的模板片段。 (index.html 实际上包括result_ajax.html。)

其中哪一个可能是最好的做事方式?

【问题讨论】:

    标签: django memcached django-queryset django-cache


    【解决方案1】:

    我会尝试这样的事情,告诉缓存装饰器为 Ajax 和非 Ajax 请求使用不同的缓存键:

    from django.views.decorators.cache import cache_page
    from django.views.decorators.vary import vary_on_headers
    
    @cache_page(60 * 60 * 12)
    @vary_on_headers('X-Requested-With')
    def items(request, pattern=None, specialurl=None):
      if request.is_ajax():
        template = "result_ajax.html"
      else: 
        template = "index.html"
    

    【讨论】:

    • 不知道这是可能的 - 谢谢你的建议!
    猜你喜欢
    • 1970-01-01
    • 2015-06-08
    • 2015-03-01
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    相关资源
    最近更新 更多