1

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:?

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.