Python JSON Persistence and Attribute Validation
Enterprise Manager and Data Management
The following implementation defines a robust system for managing enterprise data, custom attribute validation, and JSON-based persistence.
Class EnterpriseManager
The EnterpriseManager class handles the creation of data objects and executes their primary actions.
class EnterpriseManager:
def nuevo_metodo(self, param1, param2):
obj = ClaseNuevaDeDatos(param1, param2)
return obj.accion()Class AtributoNuevo
This class extends Attribute to provide specific validation logic, including regex patterns and range checks.
class AtributoNuevo(Attribute):
def __init__(self, attr_value):
self._validation_pattern = r' (regex) '
self._error_message = 'Mensaje'
self._attr_value = self._validate(attr_value)
# Logic for: si no cadena (if not string)
def __init__(self, attr_value):
self._attr_value = self.validate(attr_value)
def validate(self, attr_value):
if not isinstance(attr_value, int):
raise EntMExcep('integer')
if attr_value < 1 or attr_value > 500:
raise EntMExcep('between 1 and 500')
return attr_valueClass JsonStore
The JsonStore class provides the base functionality for searching and deleting items within a JSON file.
class JsonStore:
def find_item(self, key, value):
self.load_list_from_file()
for item in self._data_list:
if item[key] == value:
return item
return None
def delete(self, item):
self.load_list_from_file()
self._data_list = [i for i in self._data_list if i != item]
self.save_list_to_file()Class ClaseNueva
This class manages specific data parameters and integrates with the storage system.
class ClaseNueva:
def __init__(self, param1, param2):
self.__param1 = ValidarAtributo(param1).value
self.__param2 = ValidarAtributo(param2).value
@classmethod
def accion(self):
almacen = AlmacenJsonStore()
projects = projects_store.find_items_by_key('company_cif', self._cif)
if not projects:
raise EntMExcep('No projects found for this CIF')
self._project_ids = [p['project_id'] for p in projects]
# Guardar (Save):
almacen.add_item(self.to_json())
return True
def to_json(self):
return {'CAMPO1': self.__param1, 'CAMPO2': self.__param2}Class AlmacenNuevoJsonStore
A specialized implementation of JsonStore for handling new file storage and duplicates.
class AlmacenNuevoJsonStore(JsonStore):
def __init__(self):
super().__init__(FICHERONUEVO_STORE_FILE)
# Handling duplicados (duplicates):
def add_item(self, item):
self.load_list_from_file()
self._data_list.append(item)
self.save_list_to_file()Configuration and File Paths
The following configuration defines the path for the JSON data store:
# EN CFG
FICHERONUEVO_STORE_FILE = JSON_FILES_PATH + 'nuevo_fichero.json'