Advertisement
Uno-Dan

This is getting powerful.

Sep 7th, 2019
276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.83 KB | None | 0 0
  1. from os import path
  2. from copy import deepcopy
  3. from importlib.util import module_from_spec, spec_from_file_location
  4.  
  5. more_cfg = {
  6.     'level_3': {
  7.         'level_4': {
  8.             'item3': 10,
  9.             'item4': 20,
  10.         }
  11.     }
  12. }
  13.  
  14.  
  15. class Cache:
  16.     def __init__(self, *args, **kwargs):
  17.         self.nodes = args[0] if args else kwargs
  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.                 value = args[0] if args else kwargs
  47.                 nodes[key] = value
  48.  
  49.         return walk(uri, self.nodes)
  50.  
  51.     def dump(self, indent=None):
  52.         """ Dumps the contents of the cache to the screen.
  53.        The output from dump goes stdout and is used to view the cache contents.
  54.        Default indentation is a dot for each level.
  55.        :param indent:
  56.            indent (str): String to be use for indenting levels.
  57.        :return:
  58.            Nothing.
  59.        """
  60.         indent = indent if indent else '.'
  61.  
  62.         print('-------------------------------------------------------------------------------------------------------')
  63.  
  64.         if self.nodes:
  65.             def walk(_cfg, count):
  66.                 count += 1
  67.                 for key, value in _cfg.items():
  68.                     if isinstance(value, dict):
  69.                         print(indent * count, key)
  70.                         walk(value, count)
  71.                     else:
  72.                         if isinstance(value, str):
  73.                             value = f'"{value}"'
  74.                         print(indent * count, key, value)
  75.             walk(self.nodes, 0)
  76.         else:
  77.             print(' (No Data)')
  78.  
  79.         print('-------------------------------------------------------------------------------------------------------')
  80.  
  81.     def load(self, file=None):
  82.         if path.exists(file):
  83.             spec = spec_from_file_location("module.name", file)
  84.             module = module_from_spec(spec)
  85.             spec.loader.exec_module(module)
  86.             self.nodes = module.config
  87.  
  88.     def copy(self):
  89.         return Cache(deepcopy(self.nodes))
  90.  
  91.     def remove(self, uri):
  92.         """ Remove entree from cache.
  93.        Removes an entree from the cache if it exists.
  94.        :param uri:
  95.            uri (str): URI that points to the entree to remove.
  96.        :return:
  97.            Nothing.
  98.        """
  99.  
  100.         uri = uri.lstrip('/')
  101.         if self.exists(uri):
  102.             node = self.get('/'.join(uri.split('/')[:-1]))
  103.             del node[uri.split('/')[-1]]
  104.  
  105.     def exists(self, uri):
  106.         """ Test if URI exists in the cache.
  107.  
  108.        :param uri:
  109.        :return:
  110.        """
  111.         return True if self.get(uri) else False
  112.  
  113.     def destroy(self):
  114.         """ Destroy cache.
  115.        Deletes all entries in the cache.
  116.        :return:
  117.            Nothing.
  118.        """
  119.         del self.nodes
  120.         self.nodes = {}
  121.  
  122.  
  123. c = Cache()
  124. c.load('data.py')
  125.  
  126. print(c.get('level_1/level_2/item2'))
  127.  
  128. c.set('level_1/level_2/more_cfg', more_cfg)
  129.  
  130. if c.exists('level_1/level_2/more_cfg'):
  131.     print(c.get('level_1/level_2/more_cfg'))
  132.  
  133. cache_copy = c.copy()
  134. cache_copy.dump()
  135.  
  136. c.remove('level_1/level_2/item1')
  137. c.remove('level_1/level_2/item2')
  138. c.dump()
  139.  
  140. cache_copy.dump()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement