You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中获取@cache_page缓存视图的最后刷新时间?

最简单的实现方式

直接在视图函数中把最后刷新时间加入上下文即可——因为@cache_page会缓存整个渲染后的HTML响应,缓存中的时间就是视图最后一次被无缓存执行的时间,完全符合你的需求。

步骤如下:

  1. 修改视图函数,添加当前时间到上下文:
from django.views.decorators.cache import cache_page
from datetime import datetime

@cache_page(60 * 60 * 24)  # 24小时缓存
def my_view(request):
    # 获取当前时间并格式化,格式可按需调整
    last_updated = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # 你的原有业务代码
    # ...
    
    # 将时间加入上下文
    context = {
        # 其他上下文变量...
        'last_updated': last_updated
    }
    
    return render(request, 'template.html', context)
  1. 在模板中直接使用这个变量:
<p>页面最后刷新时间:{{ last_updated }}</p>

进阶:灵活复用的方式(适合多视图场景)

如果需要在多个模板中复用刷新时间逻辑,或者希望单独管理时间缓存,可以用缓存存储刷新时间,再通过自定义模板标签读取:

  1. 修改视图,在执行时将时间存入缓存:
from django.views.decorators.cache import cache_page
from django.core.cache import cache
from datetime import datetime

@cache_page(60 * 60 * 24)
def my_view(request):
    # 生成唯一缓存键,确保不同路径/用户的时间独立
    cache_key = f"last_updated_{request.path}"
    # 存储当前时间,超时时间与页面缓存一致
    cache.set(cache_key, datetime.now(), 60 * 60 * 24)
    
    # 你的原有代码
    # ...
    
    return render(request, 'template.html', context)
  1. 创建自定义模板标签:
    在项目的templatetags目录下创建cache_tags.py文件:
from django import template
from django.core.cache import cache

register = template.Library()

@register.simple_tag
def get_last_updated(request_path):
    cache_key = f"last_updated_{request_path}"
    last_updated = cache.get(cache_key)
    if last_updated:
        return last_updated.strftime("%Y年%m月%d日 %H:%M:%S")
    return "暂无刷新记录"
  1. 在模板中加载并使用标签:
{% load cache_tags %}

<p>页面最后刷新时间:{% get_last_updated request.path %}</p>

注意事项

  • 时间格式:strftime的参数可按需调整,比如"%Y年%m月%d日 %H时%M分"是更友好的中文格式。
  • 缓存键唯一性:如果视图处理带参数的URL(如/article/<id>/),用request.path作为缓存键的一部分可以确保每个页面的刷新时间独立;若希望整个视图共用一个时间,可改用视图函数名(如f"last_updated_my_view")。
  • 缓存超时一致性:进阶方式中,时间缓存的超时需与@cache_page保持一致,避免出现页面缓存过期但刷新时间缓存仍存在的情况。

内容的提问来源于stack exchange,提问作者robtus88

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:35:41