I use the API from another site that returns a pair of price URLs that my users use to buy virtual goods.
I have to cache these results for at least an hour, since they do not change the prices of their system. (And we want to save both our and bandwidth.)
After searching for a singleton in Python, I found a borg pattern that seems even cooler, so this is what I did:
def fetchPrices():
return prices
class PriceStore():
__shared_state = {}
def update(self):
if self.lastUpdate is not None and (datetime.now() - self.lastUpdate).seconds >= 3600:
self.prices = fetchPrices()
self.lastUpdate = datetime.now()
elif self.lastUpdate is not None:
return
else:
self.lastUpdate = datetime.now() - timedelta(hours=1)
self.update()
def __init__(self):
self.__dict__ = self.__shared_state
self.lastUpdate = None
self.update()
The idea is to use it as follows:
store = PriceStore()
url = store.prices['2.9900']['url']
And the store should correctly initialize and receive only new price information if the existing information is older than one hour.
, , API , PriceStore . - ? __shared_state django , ?
!