Python Library Caching
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__init__.py 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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 hashlib
  19. import hmac
  20. import json
  21. import logging
  22. import os
  23. import pickle
  24. import sys
  25. try:
  26. from config import APP_NAME as ROOT_LOGGER_NAME
  27. except ImportError:
  28. ROOT_LOGGER_NAME = 'root'
  29. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
  30. __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.
  31. For more Information read the documentation.""" % __name__.replace('_', '\_')
  32. """The Module Description"""
  33. __INTERPRETER__ = (2, 3)
  34. """The Tested Interpreter-Versions"""
  35. class property_cache_pickle(object):
  36. """
  37. Class to cache properties, which take longer on initialising than reading a file in pickle format.
  38. :param source_instance: The source instance holding the data
  39. :type source_instance: instance
  40. :param cache_filename: File name, where the properties are stored as cache
  41. :type cache_filename: str
  42. :param load_all_on_init: Optionally init behaviour control parameter. True will load all available properties from source on init, False not.
  43. .. note:: source_instance needs to have at least the following methods: uid(), keys(), data_version(), get()
  44. * uid(): returns the unique id of the source.
  45. * keys(): returns a list of all available keys.
  46. * 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).
  47. * get(key, default): returns the property for a key. If key does not exists, default will be returned.
  48. Reasons for updating the complete data set:
  49. * UID of source_instance has changed (in comparison to the cached value).
  50. * data_version is increased
  51. **Example:**
  52. .. literalinclude:: caching/_examples_/property_cache_pickle.py
  53. Will result on the first execution to the following output (with a long execution time):
  54. .. literalinclude:: caching/_examples_/property_cache_pickle_1.log
  55. With every following execution (slow for getting "two" which is not cached - see implementation):
  56. .. literalinclude:: caching/_examples_/property_cache_pickle_2.log
  57. """
  58. LOG_PREFIX = 'PickCache:'
  59. DATA_VERSION_TAG = '_property_cache_data_version_'
  60. UID_TAG = '_property_cache_uid_'
  61. def __init__(self, source_instance, cache_filename, load_all_on_init=False, callback_on_data_storage=None):
  62. self._source_instance = source_instance
  63. self._cache_filename = cache_filename
  64. self._load_all_on_init = load_all_on_init
  65. self._callback_on_data_storage = callback_on_data_storage
  66. self._cached_props = None
  67. def get(self, key, default=None):
  68. """
  69. 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).
  70. :param key: key for value to get.
  71. :param default: value to be returned, if key does not exists.
  72. :returns: value for a given key or default value.
  73. """
  74. if key in self.keys():
  75. if self._cached_props is None:
  76. self._init_cache()
  77. if self._key_filter(key) not in self._cached_props:
  78. val = self._source_instance.get(key, None)
  79. logger.debug("%s Loading property for '%s' from source instance (%s)", self.LOG_PREFIX, key, repr(val))
  80. self._cached_props[self._key_filter(key)] = val
  81. self._save_cache()
  82. else:
  83. logger.debug("%s Providing property for '%s' from cache (%s)", self.LOG_PREFIX, key, repr(self._cached_props.get(self._key_filter(key), default)))
  84. return self._cached_props.get(self._key_filter(key), default)
  85. else:
  86. logger.info("%s Key '%s' is not in cached_keys. Uncached data will be returned.", self.LOG_PREFIX, key)
  87. return self._source_instance.get(key, default)
  88. def keys(self):
  89. """
  90. Method to get the available keys (from :data:`source_instance`).
  91. """
  92. return self._source_instance.keys()
  93. def _data_version(self):
  94. if self._cached_props is None:
  95. return None
  96. else:
  97. return self._cached_props.get(self.DATA_VERSION_TAG, None)
  98. def _init_cache(self):
  99. if not self._load_cache() or self._source_instance.uid() != self._uid() or self._source_instance.data_version() > self._data_version():
  100. if self._uid() is not None and self._source_instance.uid() != self._uid():
  101. logger.debug("%s Source uid changed, ignoring previous cache data", self.LOG_PREFIX)
  102. if self._data_version() is not None and self._source_instance.data_version() > self._data_version():
  103. logger.debug("%s Data version increased, ignoring previous cache data", self.LOG_PREFIX)
  104. self._cached_props = dict()
  105. if self._load_all_on_init:
  106. self._load_source()
  107. self._cached_props[self.UID_TAG] = self._source_instance.uid()
  108. self._cached_props[self.DATA_VERSION_TAG] = self._source_instance.data_version()
  109. self._save_cache()
  110. def _load_cache(self):
  111. if os.path.exists(self._cache_filename):
  112. with open(self._cache_filename, 'rb') as fh:
  113. self._cached_props = pickle.load(fh)
  114. logger.info('%s Loading properties from cache (%s)', self.LOG_PREFIX, self._cache_filename)
  115. return True
  116. else:
  117. logger.debug('%s Cache file does not exists (yet).', self.LOG_PREFIX)
  118. return False
  119. def _key_filter(self, key):
  120. if sys.version_info >= (3, 0):
  121. tps = [str]
  122. else:
  123. tps = [str, unicode]
  124. if type(key) in tps:
  125. if key.endswith(self.DATA_VERSION_TAG) or key.endswith(self.UID_TAG):
  126. return '_' + key
  127. return key
  128. def _load_source(self):
  129. logger.debug('%s Loading all data from source - %s', self.LOG_PREFIX, repr(self._source_instance.keys()))
  130. for key in self._source_instance.keys():
  131. val = self._source_instance.get(key)
  132. self._cached_props[self._key_filter(key)] = val
  133. def _save_cache(self):
  134. with open(self._cache_filename, 'wb') as fh:
  135. pickle.dump(self._cached_props, fh)
  136. logger.info('%s cache-file stored (%s)', self.LOG_PREFIX, self._cache_filename)
  137. if self._callback_on_data_storage is not None:
  138. self._callback_on_data_storage()
  139. def _uid(self):
  140. if self._cached_props is None:
  141. return None
  142. else:
  143. return self._cached_props.get(self.UID_TAG, None)
  144. class property_cache_json(property_cache_pickle):
  145. """
  146. Class to cache properties, which take longer on initialising than reading a file in json format. See also parent :py:class:`property_cache_pickle`
  147. :param source_instance: The source instance holding the data
  148. :type source_instance: instance
  149. :param cache_filename: File name, where the properties are stored as cache
  150. :type cache_filename: str
  151. :param load_all_on_init: Optionally init behaviour control parameter. True will load all available properties from source on init, False not.
  152. .. warning::
  153. * This class uses json. You should **only** use keys of type string!
  154. * Unicode types are transfered to strings
  155. .. note:: source_instance needs to have at least the following methods: uid(), keys(), data_version(), get()
  156. * uid(): returns the unique id of the source.
  157. * keys(): returns a list of all available keys.
  158. * 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).
  159. * get(key, default): returns the property for a key. If key does not exists, default will be returned.
  160. Reasons for updating the complete data set:
  161. * UID of source_instance has changed (in comparison to the cached value).
  162. * data_version is increased
  163. **Example:**
  164. .. literalinclude:: caching/_examples_/property_cache_json.py
  165. Will result on the first execution to the following output (with a long execution time):
  166. .. literalinclude:: caching/_examples_/property_cache_json_1.log
  167. With every following execution (slow for getting "two" which is not cached - see implementation):
  168. .. literalinclude:: caching/_examples_/property_cache_json_2.log
  169. """
  170. LOG_PREFIX = 'JsonCache:'
  171. def _load_cache(self):
  172. if os.path.exists(self._cache_filename):
  173. with open(self._cache_filename, 'r') as fh:
  174. self._cached_props = json.load(fh)
  175. logger.info('%s Loading properties from cache (%s)', self.LOG_PREFIX, self._cache_filename)
  176. return True
  177. else:
  178. logger.debug('%s Cache file does not exists (yet).', self.LOG_PREFIX)
  179. return False
  180. def _save_cache(self):
  181. with open(self._cache_filename, 'w') as fh:
  182. json.dump(self._cached_props, fh, sort_keys=True, indent=4)
  183. logger.info('%s cache-file stored (%s)', self.LOG_PREFIX, self._cache_filename)
  184. if self._callback_on_data_storage is not None:
  185. self._callback_on_data_storage()