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

如何在Django中更新缓存值且不改变原超时时间?

解决方法

要在不改变原缓存超时时间的前提下更新值,你需要先获取该缓存键的剩余过期时间,再用这个剩余时间作为timeout参数调用set方法,具体实现如下:

方法一:通过缓存后端直接获取剩余TTL(推荐)

不同缓存后端(如Redis、Memcached)提供了查看键剩余生存时间(TTL)的接口,以常用的Redis为例:

# 获取Redis客户端实例
redis_client = cache.client.get_client()
# 获取myKey的剩余过期时间(单位:秒)
remaining_ttl = redis_client.ttl("myKey")

# 用剩余TTL更新缓存值,若键已过期则重新设置为一周超时
if remaining_ttl > 0:
    cache.set("myKey", new_my_value, timeout=remaining_ttl)
else:
    cache.set("myKey", new_my_value, timeout=604800)

如果使用Memcached,可以通过其自带的接口获取TTL:

memcached_client = cache.client.get_client()
# 获取值的同时返回剩余超时时间
cached_value, remaining_ttl = memcached_client.get("myKey", time=True)

# 更新缓存值
if remaining_ttl > 0:
    cache.set("myKey", new_my_value, timeout=remaining_ttl)
else:
    cache.set("myKey", new_my_value, timeout=604800)

方法二:手动存储过期时间戳(兼容所有缓存后端)

如果你的缓存后端不支持直接获取TTL,可以在初始设置缓存时,额外存储该键的过期时间戳,更新时计算剩余时间:

import time

# 初始设置缓存时,同时存储值和过期时间戳
expire_timestamp = time.time() + 604800
cache.set("myKey", {"data": my_value, "expire_at": expire_timestamp}, timeout=604800)

# 更新缓存时
cached_data = cache.get("myKey")
if cached_data:
    remaining_time = int(cached_data["expire_at"] - time.time())
    if remaining_time > 0:
        # 用剩余时间更新值,保持原过期时间
        cache.set("myKey", {"data": new_my_value, "expire_at": cached_data["expire_at"]}, timeout=remaining_time)
    else:
        # 缓存已过期,重新设置一周超时
        new_expire_timestamp = time.time() + 604800
        cache.set("myKey", {"data": new_my_value, "expire_at": new_expire_timestamp}, timeout=604800)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 09:00:00