Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from os import path, makedirs
- from json import load, dump
- from copy import deepcopy
- from importlib.util import module_from_spec, spec_from_file_location
- class Cache:
- def __init__(self, *args, **kwargs):
- self.nodes = args[0] if args else kwargs
- self.indent = '.'
- def __eq__(self, other):
- if self.nodes == other.nodes:
- return True
- return False
- def __str__(self):
- return str(self.nodes.items())
- def __repr__(self):
- data = "**{'key': 'value'}"
- return f"{self.__class__.__name__}({data})"
- def get(self, uri=None):
- if not uri:
- return self.nodes
- def walk(_uri, nodes):
- parts = _uri.split('/', 1)
- key = parts.pop(0)
- if key in nodes:
- node = nodes[key]
- if not parts:
- return node
- else:
- return walk(parts[0], node)
- return walk(uri, self.nodes)
- def set(self, uri, *args, **kwargs):
- def walk(_uri, nodes):
- parts = _uri.split('/', 1)
- key = parts.pop(0)
- if key in nodes and parts:
- return walk(parts[0], nodes[key])
- elif len(_uri.split('/')) == 1:
- nodes[key] = args[0] if args else kwargs
- return walk(uri, self.nodes)
- def dump(self, indent=None):
- """ Dumps the contents of the cache to the screen.
- The output from dump goes stdout and is used to view the cache contents.
- Default indentation is a dot for each level.
- :param indent:
- indent (str): String to be use for indenting levels.
- :return:
- Nothing.
- """
- indent = indent if indent else '.'
- print('-------------------------------------------------------------------------------------------------------')
- print('id =', id(self), '\nnodes =', self)
- if self.nodes:
- def walk(_cfg, count):
- count += 1
- for key, value in _cfg.items():
- if isinstance(value, dict):
- print(indent * count, key)
- walk(value, count)
- else:
- if isinstance(value, str):
- value = f'"{value}"'
- print(indent * count, key, f'value={value}')
- walk(self.nodes, 0)
- else:
- print(' (No Data)')
- print('-------------------------------------------------------------------------------------------------------')
- def save(self, file=None):
- if file:
- dirname = path.dirname(file)
- if dirname and not path.exists(dirname):
- makedirs(dirname)
- with open(file, 'w') as f:
- dump(self.nodes, f, indent=3)
- def load(self, file=None):
- file_type = path.splitext(file)[1].lstrip('.').lower()
- if file_type == 'py' and path.exists(file):
- spec = spec_from_file_location("module.name", file)
- module = module_from_spec(spec)
- spec.loader.exec_module(module)
- self.nodes = module.config
- if file_type == 'json' and path.exists(file):
- with open(file) as f:
- self.nodes = load(f)
- def copy(self):
- return Cache(**deepcopy(self.nodes))
- def remove(self, uri):
- """ Remove entree from cache.
- Removes an entree from the cache if it exists.
- :param uri:
- uri (str): URI that points to the entree to remove.
- :return:
- Nothing.
- """
- uri = uri.lstrip('/')
- if self.exists(uri):
- parent = self.get('/'.join(uri.split('/')[:-1]))
- del parent[uri.split('/')[-1]]
- def exists(self, uri):
- """ Test if URI exists in the cache.
- :param uri:
- :return:
- """
- return True if self.get(uri) else False
- def destroy(self):
- """ Destroy cache.
- Deletes all entries in the cache.
- :return:
- Nothing.
- """
- del self.nodes
- self.nodes = {}
- def has_nodes(self):
- if len(self.nodes):
- return True
- return False
- cache = Cache()
- cache.load('data.py')
- cache.dump()
- print('\nlevel_1/level_2/item2 = ', cache.get('level_1/level_2/item2'))
- cache.set('level_1/level_2/item2', 200)
- print('level_1/level_2/item2 = ', cache.get('level_1/level_2/item2'))
- level_4 = {
- 'level_4': {
- 'item3': 10,
- 'item4': 20,
- }
- }
- cache.set('level_1/level_2/level_3', 100)
- print(cache.get('level_1/level_2/level_3'))
- cache.dump()
- cache.set('level_1/level_2/level_3', level_4)
- cache.dump()
- cache.get('level_1/level_2/level_3').update({'level_5': {'name': 'Dan'}})
- if cache.exists('level_1/level_2/level_3'):
- print('level_1/level_2/level_3 =', cache.get('level_1/level_2/level_3'), '\n')
- cache.save('data.json')
- cache.dump()
- my_cache = cache.copy()
- my_cache.dump()
- cache.destroy()
- cache.set('p1', {'first_name': 'Dan', 'last_name': 'Huckson'})
- cache.set('p2', {'first_name': 'Geoff', 'last_name': 'Skerlan'})
- cache.dump()
- my_cache.remove('level_1/level_2/item1')
- my_cache.remove('level_1/level_2/level_3')
- my_cache.dump()
- your_cache = Cache()
- your_cache.load('data.json')
- your_cache.dump()
- # Test equality code below.
- my_cache2 = my_cache.copy()
- # uncomment the line below to test inequality.
- # my_cache.set('level_1/level_2/item2', 201)
- if my_cache == my_cache2:
- print('\nThe contents of both caches are the same!')
- if my_cache is my_cache2:
- print('my_cache2 is the same instance as my_cache.')
- else:
- print('my_cache2 is not the same instance as my_cache, but the contents are the same.')
- else:
- print('\nThe contents of both caches are not exactly same!')
- my_cache.dump()
- my_cache2.dump()
- print()
- my_cache3 = my_cache2
- if my_cache3 is my_cache2:
- print('my_cache3 is the same instance as my_cache2, notice ids.')
- my_cache3.dump()
- print()
- print('your_cache =', str(your_cache))
- print('your_cache =', repr(your_cache))
- print()
- x = Cache(abc={'item': 123}, xyx={'item': 456})
- x.dump()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement