Advertisement
Uno-Dan

See Examples Uses

Sep 7th, 2019
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.77 KB | None | 0 0
  1. from os import path, makedirs
  2. from json import load, dump
  3. from copy import deepcopy
  4. from importlib.util import module_from_spec, spec_from_file_location
  5.  
  6.  
  7. class Cache:
  8.     def __init__(self, *args, **kwargs):
  9.         self.nodes = args[0] if args else kwargs
  10.         self.indent = '.'
  11.  
  12.     def __str__(self):
  13.         return str(self.nodes.items())
  14.  
  15.     def __repr__(self):
  16.         data = "**{'key': 'value'}"
  17.         return f"{self.__class__.__name__}({data})"
  18.  
  19.     def get(self, uri=None):
  20.         if not uri:
  21.             return self.nodes
  22.  
  23.         def walk(_uri, nodes):
  24.             parts = _uri.split('/', 1)
  25.             key = parts.pop(0)
  26.  
  27.             if key in nodes:
  28.                 node = nodes[key]
  29.  
  30.                 if not parts:
  31.                     return node
  32.                 else:
  33.                     return walk(parts[0], node)
  34.  
  35.         return walk(uri, self.nodes)
  36.  
  37.     def set(self, uri, *args, **kwargs):
  38.  
  39.         def walk(_uri, nodes):
  40.             parts = _uri.split('/', 1)
  41.             key = parts.pop(0)
  42.  
  43.             if key in nodes and parts:
  44.                 return walk(parts[0], nodes[key])
  45.             elif len(_uri.split('/')) == 1:
  46.                 nodes[key] = args[0] if args else kwargs
  47.  
  48.         return walk(uri, self.nodes)
  49.  
  50.     def dump(self, indent=None):
  51.         """ Dumps the contents of the cache to the screen.
  52.        The output from dump goes stdout and is used to view the cache contents.
  53.        Default indentation is a dot for each level.
  54.        :param indent:
  55.            indent (str): String to be use for indenting levels.
  56.        :return:
  57.            Nothing.
  58.        """
  59.         indent = indent if indent else '.'
  60.  
  61.         print('-------------------------------------------------------------------------------------------------------')
  62.         print('id =', id(self), '\nnodes =', self)
  63.         if self.nodes:
  64.             def walk(_cfg, count):
  65.                 count += 1
  66.                 for key, value in _cfg.items():
  67.                     if isinstance(value, dict):
  68.                         print(indent * count, key)
  69.                         walk(value, count)
  70.                     else:
  71.                         if isinstance(value, str):
  72.                             value = f'"{value}"'
  73.                         print(indent * count, key, f'value={value}')
  74.             walk(self.nodes, 0)
  75.         else:
  76.             print(' (No Data)')
  77.  
  78.         print('-------------------------------------------------------------------------------------------------------')
  79.  
  80.     def save(self, file=None):
  81.         if file:
  82.             dirname = path.dirname(file)
  83.  
  84.             if dirname and not path.exists(dirname):
  85.                 makedirs(dirname)
  86.  
  87.             with open(file, 'w') as f:
  88.                 dump(self.nodes, f, indent=3)
  89.  
  90.     def load(self, file=None):
  91.         file_type = path.splitext(file)[1].lstrip('.').lower()
  92.  
  93.         if file_type == 'py' and path.exists(file):
  94.             spec = spec_from_file_location("module.name", file)
  95.             module = module_from_spec(spec)
  96.             spec.loader.exec_module(module)
  97.             self.nodes = module.config
  98.  
  99.         if file_type == 'json' and path.exists(file):
  100.             with open(file) as f:
  101.                 self.nodes = load(f)
  102.  
  103.     def copy(self):
  104.         return Cache(deepcopy(self.nodes))
  105.  
  106.     def remove(self, uri):
  107.         """ Remove entree from cache.
  108.        Removes an entree from the cache if it exists.
  109.        :param uri:
  110.            uri (str): URI that points to the entree to remove.
  111.        :return:
  112.            Nothing.
  113.        """
  114.  
  115.         uri = uri.lstrip('/')
  116.         if self.exists(uri):
  117.             node = self.get('/'.join(uri.split('/')[:-1]))
  118.             del node[uri.split('/')[-1]]
  119.  
  120.     def exists(self, uri):
  121.         """ Test if URI exists in the cache.
  122.  
  123.        :param uri:
  124.        :return:
  125.        """
  126.         return True if self.get(uri) else False
  127.  
  128.     def destroy(self):
  129.         """ Destroy cache.
  130.        Deletes all entries in the cache.
  131.        :return:
  132.            Nothing.
  133.        """
  134.         del self.nodes
  135.         self.nodes = {}
  136.  
  137.  
  138. c = Cache()
  139. c.load('data.py')
  140.  
  141. print(c.get('level_1/level_2/item2'))
  142.  
  143. level_4 = {
  144.     'level_4': {
  145.         'item3': 10,
  146.         'item4': 20,
  147.     }
  148. }
  149. c.set('level_1/level_2/level_3', level_4)
  150. c.get('level_1/level_2/level_3').update({'extra': {'name': 'Dan'}})
  151.  
  152. if c.exists('level_1/level_2/level_3'):
  153.     print(c.get('level_1/level_2/level_3'))
  154.  
  155. c.save('data.json')
  156.  
  157. cache_copy = c.copy()
  158. cache_copy.dump()
  159.  
  160. c.remove('level_1/level_2/item1')
  161. c.remove('level_1/level_2/level_3')
  162. c.dump()
  163.  
  164. cache_copy.dump()
  165.  
  166. my_cache = Cache()
  167. my_cache.load('data.json')
  168. my_cache.dump()
  169.  
  170. print('my_cache =', str(my_cache))
  171. print('my_cache =', repr(my_cache))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement