【问题标题】:Clear Python cachetools manually手动清除 Python 缓存工具
【发布时间】:2020-04-14 00:38:38
【问题描述】:

在这个类中,我有一个方法,我使用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)

    ...

我在这个文件中调用这个类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
...

现在我在我的main.py 中使用sessions.pyget_data 方法:

from sessions import get_data()

while the_end:
  result = get_data()
  # How can I clear cache here before going for the next loop?

我想在每个 while 循环结束后清除缓存。

我尝试了什么?

我尝试像这样更改Log__init__

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

并在while循环中删除result

while the_end:
    result = get_data()
    del result

但他们都没有帮助。

那么我怎样才能手动清除 python cachetools 或者我可以做些什么来克服这个问题?

【问题讨论】:

    标签: python python-3.x caching


    【解决方案1】:

    您可以将会话存储在类外的变量中:

    _sessions_cache = TTLCache(maxsize=200, ttl=300)
    

    然后只需调用:

    _sessions_cache.clear()
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    • 2011-11-06
    • 2021-05-30
    相关资源
    最近更新 更多