Question

I want to implement a basic cache in Python.

It's like this. I've 2 files named :- cache.py , main.py.

In my cache.py, I want to build a list every 24 hours. So, i run a cronjob cache.py every 24 hours which returns me the latest list.

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

I run main.py every minute (another cronjob). I want to print threshold_time from the cache.

main.py

import cache
print threshold_time

throws an error saying

NameError: global name 'threshold_time' is not defined

How do I implement a basic cache in Python:?

Was it helpful?

Solution

If you want multiple processes to be able to access the same data (e.g., the value of threshold_time), then you need some sort of persistent storage or a protocol for getting and setting the data. To be more specific, in your cache.py file, you need to save the value of threshold_time somewhere once you've computed it. Then your main.py can retrieve that value from wherever it's been saved.

Just from what you listed, this seems like a particularly good use case for redis, but sqlite or even a text file would also work. Each persistence strategy comes with its own levels of data integrity and complexity.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top