10

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.

What have I tried?

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?

1 Answer 1

14

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() 
Sign up to request clarification or add additional context in comments.

2 Comments

Note that the official docs state that the clear method should be thread safe (use a lock before clearing the cache).
cachetools.func decorators are thread-safe by default and have a cache_clear() method that can be used on the cache cachetools.readthedocs.io/en/stable/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.