【问题标题】:How is cache really used in Python?Python 中如何真正使用缓存?
【发布时间】:2014-07-24 08:23:35
【问题描述】:

我从来没有处理过缓存,但我想从现在开始。

我有一个 python 程序,它根据查询从网站获取结果。

问题:要进行此查询,网站需要很长时间才能加载。

想要的结果:查询一次,以某种方式存储结果,如果查询在 X 分钟内第二次出现,则检索它,否则它会过期。

这在python中是如何实现的?

【问题讨论】:

  • 你想达到什么目的?不幸的是,您的问题有点不清楚。
  • 获取结果并存储在redis,下次从redis读取?
  • 改用 memcached。它很容易跨越大多数 O/S。 stackoverflow.com/questions/868690/…

标签: python caching


【解决方案1】:

您最好的选择是使用redis。这是一个非常动态和强大的键值存储。首先,在您的系统上安装 redis,然后通过 pip 安装 redispy。然后我们跳到代码:

r = redis.StrictRedis(host='localhost', port=6379, db=0) # Make the connection with redis
query = r.get('data')  # Try to get the data from redis
if query:
   # If data exist from redis
   # Pass your data wherever you want
else:
   # If data doesn't exist in the redis
   # Get the data 
   data_from_query = **your_data_from_query**
   r.set('data', data_from_query) #Store the data in redis
   r.expire('data', 10) #Make data expire in 10 seconds

【讨论】:

  • Redis 以 Linux 为中心。我在 Windows 上。
猜你喜欢
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
  • 2012-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多