diff --git a/muk_utils/__manifest__.py b/muk_utils/__manifest__.py index 6702873..b58c41d 100644 --- a/muk_utils/__manifest__.py +++ b/muk_utils/__manifest__.py @@ -20,7 +20,7 @@ { "name": "MuK Utils", "summary": """Utility Features""", - "version": '12.0.1.0.15', + "version": '12.0.1.0.16', "category": 'Extra Tools', "license": "AGPL-3", "author": "MuK IT", diff --git a/muk_utils/tools/__init__.py b/muk_utils/tools/__init__.py index 894817f..2caf842 100644 --- a/muk_utils/tools/__init__.py +++ b/muk_utils/tools/__init__.py @@ -18,4 +18,5 @@ ################################################################################### from . import file -from . import json \ No newline at end of file +from . import json +from . import cache \ No newline at end of file diff --git a/muk_utils/tools/cache.py b/muk_utils/tools/cache.py new file mode 100644 index 0000000..a68cab3 --- /dev/null +++ b/muk_utils/tools/cache.py @@ -0,0 +1,53 @@ +################################################################################### +# +# Copyright (C) 2018 MuK IT GmbH +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +################################################################################### + +import time + +class memoize(object): + _caches = {} + _timeouts = {} + + def __init__(self, timeout=2): + self.timeout = timeout + + def collect(self): + for func in self._caches: + cleaned_cache = {} + current_time = time.time() + for key in self._caches[func]: + if (current_time - self._caches[func][key][1]) < self._timeouts[func]: + cleaned_cache[key] = self._caches[func][key] + self._caches[func] = cleaned_cache + + def __call__(self, func): + self.cache = self._caches[func] = {} + self._timeouts[func] = self.timeout + def wrapper(*args, **kwargs): + current_time = time.time() + kw = sorted(kwargs.items()) + key = (args, tuple(kw)) + try: + value = self.cache[key] + if (current_time - value[1]) > self.timeout: + raise KeyError + except KeyError: + value = self.cache[key] = (func(*args,**kwargs), current_time) + return value[0] + wrapper.func_name = func.__name__ + return wrapper \ No newline at end of file