@dataclass
class BaseModel(Base, DatabaseManager):
"""A base model class that inherits from the Base and DatabaseManager classes.
This class is abstract and not mapped to any table. It defines common attributes and methods for all models.
"""
# indicate that this class is abstract and not mapped to any table
__abstract__ = True
# define the common columns for all models
_id: int = field(metadata={"column": Column(BigInteger, primary_key=True, nullable=False)})
_attribute_type: str = field(metadata={"column": Column(String(255), nullable=False)})
# define the valid types for each attribute as a class attribute
valid_types: ClassVar[Dict[str, Type]] = {"id": int, "attribute_type": str}
def __post_init__(self):
"""Validate the types of the attributes after initialization."""
# iterate over the attributes and their values
for attr, value in self.__dict__.items():
# if the attribute is in the dictionary and the value is not of the valid type, raise a TypeError
if attr in self.valid_types and not isinstance(value, self.valid_types[attr]):
raise TypeError(f"{attr} must be of type {self.valid_types[attr].__name__}")
async def create_session(self):
"""Creates a new async session object."""
return await DatabaseManager.create_session(self)
# add a class method to create a new instance of the model
@classmethod
async def create(cls, self, **kwargs):
"""Create a new instance of the model with the given keyword arguments.
Args:
**kwargs: A dictionary of attribute names and values for the model.
Returns:
A new instance of the model.
Raises:
ValueError: If an invalid attribute name is given.
TypeError: If an invalid attribute type is given.
"""
# validate the keyword arguments
for key, value in kwargs.items():
if key not in cls.valid_types:
raise ValueError(f"Invalid attribute name: {key}")
if not isinstance(value, cls.valid_types[key]):
raise TypeError(f"{key} must be of type {cls.valid_types[key].__name__}")
# create a new instance of the model
instance = cls(**kwargs)
# add the instance to the database session
session = await cls.create_session(self)
# add the instance to the database session
session.add(instance)
# return the instance
return instance
@classmethod
async def delete(cls, self):
"""Delete the instance of the model from the session."""
# add the instance to the database session
session = await cls.create_session(self)
# add the instance to the database session
await session.delete(self)
# define the property for the id attribute
@property
def id(self) -> int:
"""Return the id of the model."""
return self._id
# define the setter for the id attribute
@id.setter
def id(self, value: int):
"""Set the id of the model with some validation."""
# check if the value is of the valid type
if not isinstance(value, int):
raise TypeError("id must be of type int")
# set the value of the attribute
self._id = value
# define the property for the attribute_type attribute
@property
def attribute_type(self) -> str:
"""Return the attribute_type of the model."""
return self._attribute_type
# define the setter for the attribute_type attribute
@attribute_type.setter
def attribute_type(self, value: str):
"""Set the attribute_type of the model with some validation."""
# check if the value is of the valid type
if not isinstance(value, str):
raise TypeError("attribute_type must be of type str")
# set the value of the attribute
self._attribute_type = value
Enhance code structure