48 lines
		
	
	
		
			1.8 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
			
		
		
	
	
			48 lines
		
	
	
		
			1.8 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
| from flask_sqlalchemy import SQLAlchemy
 | |
| from sqlalchemy import Enum, Integer, String, Date, Column
 | |
| from config import item_attributes, sql_conf
 | |
| from definitions.attribute import textAttribute, intAttribute, floatAttribute, dateAttribute, selectAttribute
 | |
| 
 | |
| # Initialize SQLAlchemy
 | |
| db = SQLAlchemy()
 | |
| 
 | |
| def create_asset_model():
 | |
|     """
 | |
|     Dynamically creates the Asset model based on the configuration in item_attributes.
 | |
|     """
 | |
|     # Define the table name and basic methods
 | |
|     attrs = {
 | |
|         '__tablename__': sql_conf.SQL_TABLE,  # Table name from config
 | |
|         '__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
 | |
|     }
 | |
| 
 | |
|     # Define columns based on item_attributes
 | |
|     for attrib in item_attributes:
 | |
|         # Determine the column type
 | |
|         if isinstance(attrib, textAttribute):
 | |
|             column_type = String(50)
 | |
|         elif isinstance(attrib, dateAttribute):
 | |
|             column_type = Date
 | |
|         elif isinstance(attrib, selectAttribute):
 | |
|             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)}")
 | |
| 
 | |
|         # Define the column with additional properties
 | |
|         attrs[attrib.attrib_name] = Column(
 | |
|             column_type,
 | |
|             primary_key=attrib.primary,
 | |
|             unique=attrib.unique,
 | |
|             nullable=not attrib.required,
 | |
|             default=attrib.default_val
 | |
|         )
 | |
| 
 | |
|     # Create the Asset class dynamically
 | |
|     Asset = type('Asset', (db.Model,), attrs)
 | |
|     return Asset
 | |
| 
 | |
| # Create the Asset model
 | |
| Asset = create_asset_model() |