Improved attribute definitions

This commit is contained in:
Candifloss 2025-02-25 16:02:11 +05:30
parent 268d205cc7
commit 346c1db607
2 changed files with 13 additions and 9 deletions

View File

@ -2,6 +2,8 @@ from datetime import datetime
import re
from typing import List, Optional, Tuple
ALLOWED_INPUT_TYPES = {"text", "number", "date", "select"}
class Attribute:
"""Base class for all attribute types."""
def __init__(
@ -32,8 +34,8 @@ class Attribute:
return f"Missing display name for attribute '{self.attrib_name}'."
if not self.html_input_type:
return f"Missing input type for attribute '{self.attrib_name}'."
if self.html_input_type not in ["text", "number", "date", "select"]:
return f"Invalid input type for attribute '{self.attrib_name}'."
if self.html_input_type not in ALLOWED_INPUT_TYPES:
return f"Invalid input type '{self.html_input_type}' for attribute '{self.attrib_name}'."
return None
@ -44,10 +46,12 @@ class textAttribute(Attribute):
attrib_name: str,
display_name: str,
regex: Optional[str] = None,
max_length: int = 50,
**kwargs
):
super().__init__(attrib_name, display_name, html_input_type="text", **kwargs)
self.regex = regex
self.max_length = max_length
def validate(self) -> Optional[str]:
"""Validate text-specific attributes."""
@ -56,7 +60,7 @@ class textAttribute(Attribute):
return error
if self.default_val is not None and self.regex is not None:
if not re.match(self.regex, str(self.default_val)):
return f"default_val does not match the regex pattern for attribute '{self.attrib_name}'."
return f"Invalid default value for '{self.attrib_name}'. It must match the pattern: {self.regex}"
return None

View File

@ -1,5 +1,5 @@
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Enum, Integer, String, Date, Column
from sqlalchemy import Enum, Integer, Float, String, Date, Column
from config import item_attributes, sql_conf
from definitions.attribute import textAttribute, intAttribute, floatAttribute, dateAttribute, selectAttribute
@ -21,7 +21,7 @@ def create_asset_model():
for attrib in item_attributes:
# Determine the column type
if isinstance(attrib, textAttribute):
column_type = String(50)
column_type = String(attrib.max_length)
elif isinstance(attrib, dateAttribute):
column_type = Date
elif isinstance(attrib, selectAttribute):
@ -40,9 +40,9 @@ def create_asset_model():
default=attrib.default_val
)
# Create the Asset class dynamically
Asset = type('Asset', (db.Model,), attrs)
return Asset
# Create the Item class dynamically
Item = type('Asset', (db.Model,), attrs)
return Item
# Create the Asset model
# Create the Item model
Asset = create_asset_model()