Python Library Caching
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

__init__.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """
  5. caching (Caching Module)
  6. ========================
  7. **Author:**
  8. * Dirk Alders <sudo-dirk@mount-mockery.de>
  9. **Description:**
  10. This Module supports functions and classes for caching e.g. properties of other instances.
  11. **Submodules:**
  12. * :class:`caching.property_cache_json`
  13. * :class:`caching.property_cache_pickle`
  14. **Unittest:**
  15. See also the :download:`unittest <caching/_testresults_/unittest.pdf>` documentation.
  16. """
  17. __DEPENDENCIES__ = []
  18. import json
  19. import logging
  20. import os
  21. import pickle
  22. import sys
  23. import time
  24. try:
  25. from config import APP_NAME as ROOT_LOGGER_NAME
  26. except ImportError:
  27. ROOT_LOGGER_NAME = 'root'
  28. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
  29. __DESCRIPTION__ = """The Module {\\tt %s} is designed to store information in {\\tt json} or {\\tt pickle} files to support them much faster then generating them from the original source file.
  30. For more Information read the documentation.""" % __name__.replace('_', '\_')
  31. """The Module Description"""
  32. __INTERPRETER__ = (3, )
  33. """The Tested Interpreter-Versions"""
  34. class property_cache_pickle(object):
  35. """
  36. Class to cache properties, which take longer on initialising than reading a file in pickle format.
  37. :param source_instance: The source instance holding the data
  38. :type source_instance: instance
  39. :param cache_filename: File name, where the properties are stored as cache
  40. :type cache_filename: str
  41. :param load_all_on_init: Optionally init behaviour control parameter. True will load all available properties from source on init, False not.
  42. .. note:: source_instance needs to have at least the following methods: uid(), keys(), data_version(), get()
  43. * uid(): returns the unique id of the source.
  44. * keys(): returns a list of all available keys.
  45. * data_version(): returns a version number of the current data (it should be increased, if the get method of the source instance returns improved values or the data structure had been changed).
  46. * get(key, default): returns the property for a key. If key does not exists, default will be returned.
  47. Reasons for updating the complete data set:
  48. * UID of source_instance has changed (in comparison to the cached value).
  49. * data_version is increased
  50. **Example:**
  51. .. literalinclude:: caching/_examples_/property_cache_pickle.py
  52. Will result on the first execution to the following output (with a long execution time):
  53. .. literalinclude:: caching/_examples_/property_cache_pickle_1.log
  54. With every following execution (slow for getting "two" which is not cached - see implementation):
  55. .. literalinclude:: caching/_examples_/property_cache_pickle_2.log
  56. """
  57. LOG_PREFIX = 'PickCache:'
  58. DATA_VERSION_TAG = '_property_cache_data_version_'
  59. STORAGE_VERSION_TAG = '_storage_version_'
  60. UID_TAG = '_property_cache_uid_'
  61. DATA_TAG = '_data_'
  62. AGE_TAG = '_age_'
  63. #
  64. STORAGE_VERSION = 1
  65. def __init__(self, source_instance, cache_filename, load_all_on_init=False, callback_on_data_storage=None, max_age=None, store_none_value=False):
  66. self._source_instance = source_instance
  67. self._cache_filename = cache_filename
  68. self._load_all_on_init = load_all_on_init
  69. self._callback_on_data_storage = callback_on_data_storage
  70. self._max_age = max_age
  71. self._store_none_value = store_none_value
  72. self._cached_props = None
  73. def get(self, key, default=None):
  74. """
  75. Method to get the cached property. If key does not exists in cache, the property will be loaded from source_instance and stored in cache (file).
  76. :param key: key for value to get.
  77. :param default: value to be returned, if key does not exists.
  78. :returns: value for a given key or default value.
  79. """
  80. if key in self.keys():
  81. if self._cached_props is None:
  82. self._init_cache()
  83. if self._max_age is None:
  84. cache_old = False
  85. else:
  86. cache_old = time.time() - self._cached_props[self.AGE_TAG].get(self._key_filter(key), 0) > self._max_age
  87. if cache_old:
  88. logger.debug("The cached value is old, cached value will be ignored")
  89. if self._key_filter(key) not in self._cached_props[self.DATA_TAG] or cache_old:
  90. val = self._source_instance.get(key, None)
  91. logger.debug("%s Loading property for '%s' from source instance (%s)", self.LOG_PREFIX, key, repr(val))
  92. if val or self._store_none_value:
  93. tm = int(time.time())
  94. logger.debug("Storing value=%s with timestamp=%d to chache", val, tm)
  95. self._cached_props[self.DATA_TAG][self._key_filter(key)] = val
  96. self._cached_props[self.AGE_TAG][self._key_filter(key)] = tm
  97. self._save_cache()
  98. else:
  99. return val
  100. else:
  101. logger.debug("%s Providing property for '%s' from cache (%s)", self.LOG_PREFIX,
  102. key, repr(self._cached_props[self.DATA_TAG].get(self._key_filter(key), default)))
  103. return self._cached_props[self.DATA_TAG].get(self._key_filter(key), default)
  104. else:
  105. logger.info("%s Key '%s' is not in cached_keys. Uncached data will be returned.", self.LOG_PREFIX, key)
  106. return self._source_instance.get(key, default)
  107. def keys(self):
  108. """
  109. Method to get the available keys (from :data:`source_instance`).
  110. """
  111. return self._source_instance.keys()
  112. def _data_version(self):
  113. if self._cached_props is None:
  114. return None
  115. else:
  116. return self._cached_props.get(self.DATA_VERSION_TAG, None)
  117. def _storage_version(self):
  118. if self._cached_props is None:
  119. return None
  120. else:
  121. return self._cached_props.get(self.STORAGE_VERSION_TAG, None)
  122. def _init_cache(self):
  123. load_cache = self._load_cache()
  124. uid = self._source_instance.uid() != self._uid()
  125. try:
  126. data_version = self._source_instance.data_version() > self._data_version()
  127. except TypeError:
  128. data_version = True
  129. try:
  130. storage_version = self._storage_version() != self.STORAGE_VERSION
  131. except TypeError:
  132. storage_version = True
  133. #
  134. if not load_cache or uid or data_version or storage_version:
  135. if self._uid() is not None and uid:
  136. logger.debug("%s Source uid changed, ignoring previous cache data", self.LOG_PREFIX)
  137. if self._data_version() is not None and data_version:
  138. logger.debug("%s Data version increased, ignoring previous cache data", self.LOG_PREFIX)
  139. if storage_version:
  140. logger.debug("%s Storage version changed, ignoring previous cache data", self.LOG_PREFIX)
  141. self._cached_props = {self.AGE_TAG: {}, self.DATA_TAG: {}}
  142. if self._load_all_on_init:
  143. self._load_source()
  144. self._cached_props[self.UID_TAG] = self._source_instance.uid()
  145. self._cached_props[self.DATA_VERSION_TAG] = self._source_instance.data_version()
  146. self._cached_props[self.STORAGE_VERSION_TAG] = self.STORAGE_VERSION
  147. self._save_cache()
  148. def _load_cache(self):
  149. if os.path.exists(self._cache_filename):
  150. with open(self._cache_filename, 'rb') as fh:
  151. self._cached_props = pickle.load(fh)
  152. logger.info('%s Loading properties from cache (%s)', self.LOG_PREFIX, self._cache_filename)
  153. return True
  154. else:
  155. logger.debug('%s Cache file does not exists (yet).', self.LOG_PREFIX)
  156. return False
  157. def _key_filter(self, key):
  158. return key
  159. def _load_source(self):
  160. logger.debug('%s Loading all data from source - %s', self.LOG_PREFIX, repr(self._source_instance.keys()))
  161. for key in self._source_instance.keys():
  162. val = self._source_instance.get(key)
  163. self._cached_props[self.DATA_TAG][self._key_filter(key)] = val
  164. self._cached_props[self.AGE_TAG][self._key_filter(key)] = int(time.time())
  165. def _save_cache(self):
  166. with open(self._cache_filename, 'wb') as fh:
  167. pickle.dump(self._cached_props, fh)
  168. logger.info('%s cache-file stored (%s)', self.LOG_PREFIX, self._cache_filename)
  169. if self._callback_on_data_storage is not None:
  170. self._callback_on_data_storage()
  171. def _uid(self):
  172. if self._cached_props is None:
  173. return None
  174. else:
  175. return self._cached_props.get(self.UID_TAG, None)
  176. class property_cache_json(property_cache_pickle):
  177. """
  178. Class to cache properties, which take longer on initialising than reading a file in json format. See also parent :py:class:`property_cache_pickle`
  179. :param source_instance: The source instance holding the data
  180. :type source_instance: instance
  181. :param cache_filename: File name, where the properties are stored as cache
  182. :type cache_filename: str
  183. :param load_all_on_init: Optionally init behaviour control parameter. True will load all available properties from source on init, False not.
  184. .. warning::
  185. * This class uses json. You should **only** use keys of type string!
  186. * Unicode types are transfered to strings
  187. .. note:: source_instance needs to have at least the following methods: uid(), keys(), data_version(), get()
  188. * uid(): returns the unique id of the source.
  189. * keys(): returns a list of all available keys.
  190. * data_version(): returns a version number of the current data (it should be increased, if the get method of the source instance returns improved values or the data structure had been changed).
  191. * get(key, default): returns the property for a key. If key does not exists, default will be returned.
  192. Reasons for updating the complete data set:
  193. * UID of source_instance has changed (in comparison to the cached value).
  194. * data_version is increased
  195. **Example:**
  196. .. literalinclude:: caching/_examples_/property_cache_json.py
  197. Will result on the first execution to the following output (with a long execution time):
  198. .. literalinclude:: caching/_examples_/property_cache_json_1.log
  199. With every following execution (slow for getting "two" which is not cached - see implementation):
  200. .. literalinclude:: caching/_examples_/property_cache_json_2.log
  201. """
  202. LOG_PREFIX = 'JsonCache:'
  203. def _load_cache(self):
  204. if os.path.exists(self._cache_filename):
  205. with open(self._cache_filename, 'r') as fh:
  206. self._cached_props = json.load(fh)
  207. logger.info('%s Loading properties from cache (%s)', self.LOG_PREFIX, self._cache_filename)
  208. return True
  209. else:
  210. logger.debug('%s Cache file does not exists (yet).', self.LOG_PREFIX)
  211. return False
  212. def _save_cache(self):
  213. with open(self._cache_filename, 'w') as fh:
  214. json.dump(self._cached_props, fh, sort_keys=True, indent=4)
  215. logger.info('%s cache-file stored (%s)', self.LOG_PREFIX, self._cache_filename)
  216. if self._callback_on_data_storage is not None:
  217. self._callback_on_data_storage()