tiramisu/tiramisu/storage/util.py

74 lines
2.5 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
2014-01-20 14:53:08 +01:00
"utils used by storage"
2017-07-08 15:59:56 +02:00
# Copyright (C) 2013-2017 Team tiramisu (see AUTHORS for all contributors)
#
2013-09-22 22:33:09 +02:00
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
2013-09-22 22:33:09 +02:00
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
2013-09-22 22:33:09 +02:00
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# ____________________________________________________________
from ..setting import owners
2013-09-22 20:57:52 +02:00
class Cache(object):
2013-09-22 20:57:52 +02:00
__slots__ = ('_cache', '_storage')
key_is_path = False
def __init__(self, storage):
self._cache = {}
2013-09-22 20:57:52 +02:00
self._storage = storage
def setcache(self, path, val, time, index):
2017-07-08 15:59:56 +02:00
"""add val in cache for a specified path
if slave, add index
"""
self._cache.setdefault(path, {})[index] = (val, time)
def getcache(self, path, exp, index):
value, created = self._cache[path][index]
2013-09-07 22:37:13 +02:00
if created is None or exp <= created:
return True, value
2017-02-03 23:39:24 +01:00
return False, None # pragma: no cover
2017-07-08 15:59:56 +02:00
def delcache(self, path):
"""remove cache for a specified path
"""
if path in self._cache:
del self._cache[path]
def hascache(self, path, index):
""" path is in the cache
:param path: the path's option
"""
return path in self._cache and index in self._cache[path]
2013-09-07 17:25:22 +02:00
def reset_expired_cache(self, exp):
2016-03-19 21:27:37 +01:00
cache_keys = list(self._cache.keys())
for key in cache_keys:
key_cache_keys = list(self._cache[key].keys())
for index in key_cache_keys:
val, created = self._cache[key][index]
if created is not None and exp > created:
del(self._cache[key][index])
if self._cache[key] == {}:
del(self._cache[key])
2013-09-07 17:25:22 +02:00
def reset_all_cache(self):
"empty the cache"
self._cache.clear()
2013-09-07 17:25:22 +02:00
def get_cached(self, context):
"""return all values in a dictionary
example: {'path1': {'index1': ('value1', 'time1')}, 'path2': {'index2': ('value2', 'time2', )}}
"""
return self._cache