Django, Borg Template, API Calls, Caching Results

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():
    #uses urllib2.urlopen() to fetch prices
    #parses results with ElementTree
    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 , ?

!

+3
3

, API , PriceStore . - ?

, :

def __init__(self):
    self.__dict__ = self.__shared_state
    self.lastUpdate = None

self.lastUpdate = None , self.update() self.lastUpdate None - !

self.lastUpdate = None __init__ , ,

lastUpdate = None

. __shared_state = {} , . , .

+4

, PriceStore self.lastUpdate None ( - ). , , .

:

class PriceStore():
    __shared_state = {'lastUpdate': None}

, , , , Django, . .

+1

__init__ self.lastUpdate = None. .

, :

A = PriceStore()

# some time later

B = PriceStore()

A.lastUpdate == , !

if "lastUpdate" not in self.__dict__:
    self.lastUpdate = None

.

0

Source: https://habr.com/ru/post/1757025/