python-snippets/pseudodb/pseudodb.py

56 lines
1.9 KiB
Python
Raw Normal View History

2024-07-17 21:30:12 +00:00
import importlib
2024-07-18 23:24:32 +00:00
from array import array
2024-07-17 21:30:12 +00:00
class PseudoDB:
def __init__(self, datasource="default.data"):
self.datasource = datasource
self.data = self.load_data()
def load_data(self):
module_name = self.datasource.replace('.py', '')
try:
module = importlib.import_module(module_name)
return module
except ImportError:
print(f"Data module '{module_name}' not found.")
return None
2024-07-17 21:59:13 +00:00
def get_collections(self):
2024-07-17 21:30:12 +00:00
# Check if default has been successfully loaded
if self.data is not None:
attr_names = []
for attr_name in dir(self.data):
2024-07-19 17:48:29 +00:00
if not attr_name.startswith('__') and attr_name != 'ar':
2024-07-18 23:24:32 +00:00
collection = getattr(self.data, attr_name)
attr_names.append((attr_name, type(collection)))
# Sort the collections by their name before returning
return sorted(attr_names, key=lambda x: x[0])
2024-07-17 21:30:12 +00:00
else:
return []
def get_keys(self, attr_name):
if self.data is not None:
collection = getattr(self.data, attr_name)
if isinstance(collection, dict):
return list(collection.keys())
else:
return {}
2024-07-18 23:24:32 +00:00
def get_values(self, attr_name, key=None):
2024-07-17 21:30:12 +00:00
if self.data is not None:
collection = getattr(self.data, attr_name)
if isinstance(collection, dict):
return list(collection[key])
2024-07-18 23:24:32 +00:00
elif isinstance(collection, list):
return collection
elif isinstance(collection, array):
return collection
elif isinstance(collection, tuple):
2024-07-17 21:30:12 +00:00
return collection
2024-07-18 23:24:32 +00:00
else: # assume it's a string
return str(collection)
2024-07-17 21:30:12 +00:00
else:
return None