简体   繁体   English

如何改善Python中的简单缓存机制?

[英]How to improve a simple caching mechanism in Python?

just registered so I could ask this question. 刚刚注册,所以我可以问这个问题。

Right now I have this code that prevents a class from updating more than once every five minutes: 现在,我有这段代码可以防止一个类每五分钟更新一次:

now = datetime.now()
delta = now - myClass.last_updated_date
seconds = delta.seconds

if seconds > 300
    update(myClass)     
else
    retrieveFromCache(myClass)

I'd like to modify it by allowing myClass to update twice per 5 minutes, instead of just once. 我想通过允许myClass每5分钟更新两次,而不是一次更新来进行修改。

I was thinking of creating a list to store the last two times myClass was updated, and comparing against those in the if statement, but I fear my code will get convoluted and harder to read if I go that route. 我当时在考虑创建一个列表来存储myClass最近两次更新的内容,并与if语句中的内容进行比较,但是我担心如果走那条路,我的代码会变得费解并且难以阅读。

Is there a simpler way to do this? 有没有更简单的方法可以做到这一点?

You could do it with a simple counter. 您可以使用一个简单的计数器来完成。 Concept is get_update_count tracks how often the class is updated. 概念是get_update_count跟踪类更新的频率。

if seconds > 300 or get_update_count(myClass) < 2:
    #and update updatecount
    update(myClass)     
else:
    #reset update count
    retrieveFromCache(myClass)

Im not sure how you uniquely identify myClass. 我不确定您如何唯一地标识myClass.

update_map = {}

def update(instance):
     #do the update
     update_map[instance] = update_map.get(instance,0)+1

def get_update_count(instance):
     return update_map[instance] or 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM