In this class I have a method which I cache its result using cachetools:
from cachetools import cached, TTLCache
class Log:
@cached(TTLCache(maxsize=200, ttl=300))
def get_sessions(self, user_id):
query = """select * from comprehensive_log.sessions where user_id = %s order by start DESC limit 50"""
user_sessions = self.fetch_data_from_log(query, (user_id,))
return user_sessions
def get_last_session(self, user_id_arg):
user_sessions = self.get_sessions(user_id_arg)
...
I call this class in this file sessions.py:
from src.OO_log import Log
log_object = Log()
def get_data():
user_list = get_user_list_from_database()
for user in user_list:
log_object.get_last_session(user.id)
return True
...
Now I use get_data method of sessions.py in my main.py:
from sessions import get_data()
while the_end:
result = get_data()
# How can I clear cache here before going for the next loop?
I want to clear the cache after the end of each while loop.
I tried changing the Log class __init__ like this:
class Log:
def __init__(self):
self.get_sessions = cached(TTLCache(maxsize=200, ttl=300))(self.get_sessions)
def get_sessions(self, user_id):
query = """select * from comprehensive_log.sessions where user_id = %s order by start DESC limit 50"""
user_sessions = self.fetch_data_from_log(query, (user_id,))
return user_sessions
and deleting result in while loop:
while the_end:
result = get_data()
del result
But none of them helped.
So how can I clear python cachetools manually or is there anything else I can do to overcome this problem?
You can store the sessions in a variable outside the class:
_sessions_cache = TTLCache(maxsize=200, ttl=300)
and then just call:
_sessions_cache.clear()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With