flask_crud_app/definitions/models.py

48 lines
1.8 KiB
Python
Raw Normal View History

2025-01-29 05:27:19 +00:00
from flask_sqlalchemy import SQLAlchemy
2025-02-11 20:45:25 +00:00
from sqlalchemy import Enum, Integer, String, Date, Column
from config import item_attributes, sql_conf
from definitions.attribute import textAttribute, intAttribute, floatAttribute, dateAttribute, selectAttribute
2025-01-29 05:27:19 +00:00
# Initialize SQLAlchemy
2025-01-29 05:27:19 +00:00
db = SQLAlchemy()
2025-02-11 20:45:25 +00:00
def create_asset_model():
"""
Dynamically creates the Asset model based on the configuration in item_attributes.
"""
# Define the table name and basic methods
2025-02-11 20:45:25 +00:00
attrs = {
'__tablename__': sql_conf.SQL_TABLE, # Table name from config
2025-02-11 20:45:25 +00:00
'__init__': lambda self, **kwargs: self.__dict__.update(kwargs), # Constructor
'__repr__': lambda self: f"<Asset {getattr(self, next(attrib.attrib_name for attrib in item_attributes if attrib.primary))}>" # Representation
2025-02-11 20:45:25 +00:00
}
2025-01-29 05:27:19 +00:00
# Define columns based on item_attributes
2025-02-19 10:38:10 +00:00
for attrib in item_attributes:
# Determine the column type
if isinstance(attrib, textAttribute):
2025-02-11 20:45:25 +00:00
column_type = String(50)
elif isinstance(attrib, dateAttribute):
2025-02-11 20:45:25 +00:00
column_type = Date
elif isinstance(attrib, selectAttribute):
2025-02-19 10:38:10 +00:00
column_type = Enum(*attrib.options)
elif isinstance(attrib, (intAttribute, floatAttribute)):
column_type = Integer if isinstance(attrib, intAttribute) else Float
else:
raise ValueError(f"Unsupported attribute type: {type(attrib)}")
2025-01-29 10:05:36 +00:00
2025-02-11 20:45:25 +00:00
# Define the column with additional properties
2025-02-19 10:38:10 +00:00
attrs[attrib.attrib_name] = Column(
2025-02-11 20:45:25 +00:00
column_type,
2025-02-19 10:38:10 +00:00
primary_key=attrib.primary,
unique=attrib.unique,
nullable=not attrib.required,
default=attrib.default_val
2025-02-11 20:45:25 +00:00
)
2025-01-29 10:05:36 +00:00
2025-02-11 20:45:25 +00:00
# Create the Asset class dynamically
Asset = type('Asset', (db.Model,), attrs)
return Asset
2025-01-29 10:05:36 +00:00
2025-02-11 20:45:25 +00:00
# Create the Asset model
Asset = create_asset_model()