我有一个 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 结果,反之亦然。
所以我需要做的是找出缓存的其他方式。我可以想到以下选项:
- 仅缓存数据库查询,一次最多缓存一天。这可能吗?
- 在
result_ajax.html
中缓存实际显示结果的模板片段。 (index.html
实际上包含result_ajax.html
。)
以下哪一个可能是最好的做事方式?
最佳答案
我会尝试像这样告诉缓存装饰器对 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"
关于Django:如何处理 Ajax 请求不同 View 中的缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17113769/