【问题标题】:Does Django Cache Clear Itself After ExpirationDjango缓存过期后会自动清除吗
【发布时间】:2018-09-08 15:47:15
【问题描述】:

我目前正在使用 Memcache 和 Django 来缓存从外部 API 请求的数据,因此我不会压倒他们的服务器。目前我的代码如下所示:

# CACHE CURRENT PRICE
cache_key_price = str(stock.id)+'_price' # needs to be unique
cache_key_change = str(stock.id)+'_change'
cache_keychange_pct = str(stock.id)+'_changePct'

cache_time = 60 * 5 # time in seconds for cache to be valid
price_data = cache.get(cache_key_price) # returns None if no key-value pair
change_data = cache.get(cache_key_change) # returns None if no key-value pair
changePct_data = cache.get(cache_keychange_pct) # returns None if no key-value pair

if not price_data:
    delayed_price, change, changePct = get_quote(stock.ticker)

    price_data = delayed_price
    change_data = change
    changePct_data = changePct

cache.set(cache_key_price, price_data, cache_time)
cache.set(cache_key_change, change_data, cache_time)
cache.set(cache_keychange_pct, changePct_data, cache_time)

context_dict['delayed_price'] = cache.get(cache_key_price)
context_dict['change'] = cache.get(cache_key_change)
context_dict['changePct'] = cache.get(cache_keychange_pct)

我对缓存有点陌生,我很好奇 5 分钟后缓存是否会自行清除,data 将返回 None 触发if not data: 代码位以获取更新数据。

提前感谢您的帮助!

【问题讨论】:

  • 代码看起来没问题。您是否遇到任何错误或意外行为?
  • 对不起,我刚刚更新了一秒钟,您介意再看一下吗。没有奇怪的行为,但我是缓存的菜鸟,这是我第一个使用它的实时项目,所以我只是想确定一下。
  • 你应该缩进这3个语句cache.ser(...);它们只能在if not price_data: 内运行。除此之外,代码应该可以工作;试试看吧。
  • 澄清一下,cache.set() 应该只在if not price_data: 被触发时运行。而if not price_data是在5分钟后缓存过期时触发的?

标签: django caching memcached


【解决方案1】:

这是您的代码的简化版本(只有 1 个键,而不是全部 3 个键);您可以扩展它以满足您的需求。

我做了两处改动:首先,cache.set(..) 语句需要在if not price_data: 块内,这样它只在缓存为空(或过期)时运行。

其次,您应该使用变量price_data 加载到上下文中;这样您就无需再次致电cache.get(..)

cache_key_price = str(stock.id)+'_price' # needs to be unique
cache_time = 60 * 5 # time in seconds for cache to be valid
price_data = cache.get(cache_key_price) # returns None if no key-value pair

if not price_data:
    delayed_price, change, changePct = get_quote(stock.ticker)
    price_data = delayed_price
    cache.set(cache_key_price, price_data, cache_time)

context_dict['delayed_price'] = price_data

【讨论】:

    猜你喜欢
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    • 2019-07-11
    • 2014-04-11
    • 1970-01-01
    相关资源
    最近更新 更多