我想在Python中实现基本缓存。
就像这样。我有两个名为的文件: - cache.py
,main.py
。
在我的cache.py中,我想每24小时建一个列表。所以,我每24小时运行一次cronjob cache.py
,它会返回最新列表。
cache.py
def get_hubcode_threshold_time():
global threshold_time
hub_alarm_obj = HubAlarm.objects.all().values('time').distinct()
for obj in hub_alarm_obj:
threshold_time.append(obj.time)
if __name__ == "__main__":
get_hubcode_threshold_time()
print threshold_time
我每分钟都跑main.py
(另一个cronjob)。我想从缓存中打印threshold_time。
main.py
import cache
print threshold_time
抛出错误说
NameError: global name 'threshold_time' is not defined
如何在Python中实现基本缓存:?
答案 0 :(得分:2)
如果您希望多个进程能够访问相同的数据(例如,threshold_time
的值),那么您需要某种持久存储或用于获取和设置数据的协议。更具体地说,在cache.py
文件中,您需要在计算完毕后将threshold_time
的值保存在某处。然后,您main.py
可以从保存的任何地方检索该值。
从你列出的内容来看,这对redis来说似乎是一个特别好的用例,但是sqlite甚至是文本文件也可以。每种持久性策略都有自己的数据完整性和复杂性。