[Django]-Django, Borg pattern, API calls, caching results

4πŸ‘

βœ…

I seem to be hitting their API with
every time that PriceStore is
initialized, though. Can anyone spot
my problem?

Yep, it’s easy to spot:

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

the self.lastUpdate = None absolutely guarantees that the immediately following call to self.update() will find self.lastUpdateβ€˜s value to be None β€” you just forced it to be so!

Remove that self.lastUpdate = None in the __init__ and, for example, use instead a

lastUpdate = None

at class body level, e.g. just after the __shared_state = {} assignment and with the same alignment as that assignment. That will make things work as you intend.

πŸ‘€Alex Martelli

1πŸ‘

Your main problem is that when you create a new PriceStore, you set self.lastUpdate to None (in your second-to-last line). So although they all share state, every new object clobbers the state.

Instead do this:

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

Another problem you might face is that depending on how your Django is deployed, you may be using more than one process. Each one would have its own copy of the shared state.

0πŸ‘

In __init__ you set self.lastUpdate = None. Don’t do that.

Specifically, consider the following code:

A = PriceStore()

# some time later

B = PriceStore()

Now A.lastUpdate == None, which you didn’t want! Instead, try

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

That way you never overwrite it.

πŸ‘€Katriel

Leave a comment