Home Information - Your home, your data, organized.
Python
Some renaming and refactoring of SimEntity wrapper class.
Anthony Cassandra0075d09b5c78
diff --git a/src/hi/simulator/admin.py b/src/hi/simulator/admin.pyindex 933d039b..d48f641e 100644--- a/src/hi/simulator/admin.py+++ b/src/hi/simulator/admin.py@@ -11,14 +11,14 @@ class DbSimEntityAdmin(admin.ModelAdmin):list_display = ('sim_profile','simulator_id',- 'entity_class_name',+ 'entity_class_id','entity_type_str','editable_fields','updated_datetime','created_datetime',)- search_fields = ['entity_class_name']+ search_fields = ['entity_class_id']readonly_fields = ( 'updated_datetime', 'created_datetime', )diff --git a/src/hi/simulator/forms.py b/src/hi/simulator/forms.pyindex f66619e5..7e78ff0e 100644--- a/src/hi/simulator/forms.py+++ b/src/hi/simulator/forms.py@@ -22,7 +22,7 @@ class SimEntityForm( forms.Form ):Dynamically build a Django form from a subclass of SimEntity."""- DATACLASS_TO_FORM_FIELD = {+ DATA_TYPE_TO_FORM_FIELD = {str: forms.CharField,int: forms.IntegerField,float: forms.FloatField,@@ -33,11 +33,9 @@ class SimEntityForm( forms.Form ):def __init__(self, sim_entity_class: Type[ SimEntity ], *args, initial = None, **kwargs):super().__init__(*args, **kwargs)- self._sim_entity_class = sim_entity_class-for field in fields( sim_entity_class ):field_type = field.type- form_field_class = self.DATACLASS_TO_FORM_FIELD.get( field_type, None )+ form_field_class = self.DATA_TYPE_TO_FORM_FIELD.get( field_type, None )if not form_field_class:raise ValueError( f'Unsupported field type: {field_type}' )@@ -51,7 +49,3 @@ class SimEntityForm( forms.Form ):)continuereturn-- @property- def sim_entity_name(self):- return self._sim_entity_class.__name__diff --git a/src/hi/simulator/migrations/0006_rename_entity_class_name_dbsimentity_entity_class_id.py b/src/hi/simulator/migrations/0006_rename_entity_class_name_dbsimentity_entity_class_id.pynew file mode 100644index 00000000..a073be5d--- /dev/null+++ b/src/hi/simulator/migrations/0006_rename_entity_class_name_dbsimentity_entity_class_id.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.15 on 2024-12-24 18:45++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("simulator", "0005_remove_dbsimentity_name"),+ ]++ operations = [+ migrations.RenameField(+ model_name="dbsimentity",+ old_name="entity_class_name",+ new_name="entity_class_id",+ ),+ ]diff --git a/src/hi/simulator/migrations/0007_alter_dbsimentity_entity_class_id.py b/src/hi/simulator/migrations/0007_alter_dbsimentity_entity_class_id.pynew file mode 100644index 00000000..4712b654--- /dev/null+++ b/src/hi/simulator/migrations/0007_alter_dbsimentity_entity_class_id.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.15 on 2024-12-24 18:45++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("simulator", "0006_rename_entity_class_name_dbsimentity_entity_class_id"),+ ]++ operations = [+ migrations.AlterField(+ model_name="dbsimentity",+ name="entity_class_id",+ field=models.CharField(max_length=255, verbose_name="Entity Class Id"),+ ),+ ]diff --git a/src/hi/simulator/models.py b/src/hi/simulator/models.pyindex 5b86b054..85a55339 100644--- a/src/hi/simulator/models.py+++ b/src/hi/simulator/models.py@@ -41,8 +41,8 @@ class DbSimEntity(models.Model):max_length = 64,null = False, blank = False,)- entity_class_name = models.CharField(- 'Entity Class Name',+ entity_class_id = models.CharField(+ 'Entity Class Id',max_length = 255,null = False, blank = False,)diff --git a/src/hi/simulator/simulator.py b/src/hi/simulator/simulator.pyindex 2e1993b7..8d2302cc 100644--- a/src/hi/simulator/simulator.py+++ b/src/hi/simulator/simulator.py@@ -2,7 +2,7 @@ from typing import List, Typefrom hi.apps.common.singleton import Singleton-from .transient_models import SimEntity, SimEntityClassWrapper+from .transient_models import SimEntity, SimEntityClassDataclass Simulator( Singleton ):@@ -48,9 +48,8 @@ class Simulator( Singleton ):raise NotImplementedError('Subclasses must override this method.')@property- def sim_entity_class_wrapper_list(self) -> List[ SimEntityClassWrapper ]:- return [ SimEntityClassWrapper( sim_entity_class = x )- for x in self.get_sim_entity_class_list() ]+ def sim_entity_class_data_list(self) -> List[ SimEntityClassData ]:+ return [ SimEntityClassData( sim_entity_class = x ) for x in self.get_sim_entity_class_list() ]def add_sim_entity( self, sim_entity : SimEntity ):self.validate_new_sim_entity( sim_entity = sim_entity )diff --git a/src/hi/simulator/simulator_manager.py b/src/hi/simulator/simulator_manager.pyindex 8126bade..0a8d96af 100644--- a/src/hi/simulator/simulator_manager.py+++ b/src/hi/simulator/simulator_manager.py@@ -1,7 +1,7 @@from asgiref.sync import sync_to_asyncimport loggingfrom threading import Lock-from typing import Dict+from typing import Dict, Listfrom django.apps import apps@@ -12,7 +12,7 @@ from hi.apps.common.singleton import Singletonfrom .models import DbSimEntity, SimProfilefrom .simulator import Simulatorfrom .simulator_data import SimulatorData-from .transient_models import SimEntity, SimEntityClassWrapper+from .transient_models import SimEntity, SimEntityClassDatalogger = logging.getLogger(__name__)@@ -27,7 +27,7 @@ class SimulatorManager( Singleton ):self._data_lock = Lock()return- def get_sim_profile_list(self):+ def get_sim_profile_list(self) -> List[ SimProfile ]:return list( SimProfile.objects.all().order_by('name') )@property@@ -35,6 +35,8 @@ class SimulatorManager( Singleton ):return self._current_sim_profiledef set_sim_profile( self, sim_profile : SimProfile ):+ should_reinitialize_simulators = bool( not sim_profile+ or ( sim_profile != self._current_sim_profile ))if not sim_profile:self._initialize_sim_profile()else:@@ -42,17 +44,17 @@ class SimulatorManager( Singleton ):sim_profile.save()self._current_sim_profile = sim_profile- if sim_profile != self._current_sim_profile:+ if should_reinitialize_simulators:self._initialize_simulators()returndef get_simulator( self, simulator_id : str ) -> Simulator:simulator_data = self._simulator_data_map.get( simulator_id )- if not simulator_id:+ if not simulator_data:raise KeyError( f'Simulator id "{simulator_id}" not found.' )return simulator_data.simulator- def get_simulator_list(self):+ def get_simulator_list(self) -> List[ Simulator ]:simulator_list = [ x.simulator for x in self._simulator_data_map.values() ]simulator_list.sort( key = lambda item : item.label )return simulator_list@@ -60,9 +62,12 @@ class SimulatorManager( Singleton ):def add_sim_entity( self,simulator : Simulator,sim_entity : SimEntity ):- # We add to the simulator first to allow it to check for any- # simulator-specific errors before saving to the database. That- # means we also remove it should something go wrong with saving it.++ # Before saving to the database, we add to the simulator instance+ # so that it can check for any simulator-specific errors and raise+ # a SimEntityValidationError if needed. That means we also must+ # remove it from the simulatior instance should something go wrong+ # after that while saving it to the database.#simulator.add_sim_entity( sim_entity = sim_entity )@@ -72,13 +77,13 @@ class SimulatorManager( Singleton ):if not simulator_data:raise KeyError( f'No data found for simulator id = {simulator.id}' )- sim_entity_class_wrapper = SimEntityClassWrapper( sim_entity_class = sim_entity.__class__ )+ sim_entity_class_data = SimEntityClassData( sim_entity_class = sim_entity.__class__ )db_sim_entity = DbSimEntity.objects.create(sim_profile = self.current_sim_profile,simulator_id = simulator.id,- entity_class_name = sim_entity_class_wrapper.name,- entity_type = sim_entity_class_wrapper.entity_type,+ entity_class_id = sim_entity_class_data.class_id,+ entity_type = sim_entity_class_data.entity_type,editable_fields = sim_entity.to_json_dict())@@ -86,7 +91,7 @@ class SimulatorManager( Singleton ):except Exception as e:simulator.remove_sim_entity( sim_entity = sim_entity )- raise+ raise efinally:self._data_lock.release()@@ -156,12 +161,11 @@ class SimulatorManager( Singleton ):for simulator_id, simulator_data in self._simulator_data_map.items():simulator = simulator_data.simulator- sim_entity_class_list = simulator.get_sim_entity_class_list()- logger.debug( f'Adding {len(sim_entity_class_list)} entity class to simulator {simulator_id}.' )- for sim_entity_class in sim_entity_class_list:- sim_entity_class_wrapper = SimEntityClassWrapper( sim_entity_class = sim_entity_class )- class_name = sim_entity_class_wrapper.name- simulator_data.sim_entity_class_map[class_name] = sim_entity_class+ sim_entity_class_data_list = simulator.sim_entity_class_data_list+ logger.debug( f'Adding {len(sim_entity_class_data_list)} entities to simulator {simulator_id}.' )+ for sim_entity_class_data in osim_entity_class_data_list:+ class_id = sim_entity_class_data.class_id+ simulator_data.sim_entity_class_map[class_id] = sim_entity_class_data.sim_entity_classcontinuecontinuereturn@@ -180,10 +184,10 @@ class SimulatorManager( Singleton ):continuesim_entity_class_map = simulator_data.sim_entity_class_map- class_name = db_sim_entity.entity_class_name- sim_entity_class = sim_entity_class_map.get( class_name )+ class_id = db_sim_entity.entity_class_id+ sim_entity_class = sim_entity_class_map.get( class_id )if not sim_entity_class:- logger.warning( f'Entity class "{class_name}" not found for simulator "{simulator_id}"' )+ logger.warning( f'Entity class "{class_id}" not found for simulator "{simulator_id}"' )continuesim_entity = sim_entity_class.from_json_dict( db_sim_entity.editable_fields )diff --git a/src/hi/simulator/templates/simulator/modals/sim_entity_add.html b/src/hi/simulator/templates/simulator/modals/sim_entity_add.htmlindex 29c54012..809b2366 100644--- a/src/hi/simulator/templates/simulator/modals/sim_entity_add.html+++ b/src/hi/simulator/templates/simulator/modals/sim_entity_add.html@@ -1,7 +1,7 @@{% extends "modals/action_with_cancel.html" %}{% block preamble %}-<form action="{% url 'simulator_entity_add' simulator_id=simulator.id class_name=sim_entity_class_wrapper.name %}" method="post"+<form action="{% url 'simulator_entity_add' simulator_id=simulator.id class_id=sim_entity_class_data.class_id %}" method="post"class="form" data-async="modal">{% csrf_token %}{% endblock %}@@ -12,7 +12,7 @@ Add {{ simulator.label }} Entity{% block body %}<div>- <div class="h3">{{ sim_entity_class_wrapper.label }}</div>+ <div class="h3">{{ sim_entity_class_data.class_label }}</div>{% include "simulator/panes/sim_entity_form.html" with sim_entity_form=sim_entity_form %}</div>{% endblock %}diff --git a/src/hi/simulator/templates/simulator/panes/simulator_control_tabs.html b/src/hi/simulator/templates/simulator/panes/simulator_control_tabs.htmlindex 693eb6ac..d4fcbfc9 100644--- a/src/hi/simulator/templates/simulator/panes/simulator_control_tabs.html+++ b/src/hi/simulator/templates/simulator/panes/simulator_control_tabs.html@@ -30,14 +30,14 @@</button><div class="dropdown-menu dropdown-menu-right"role="menu" aria-labelledby="hi-sim-entity-{{ simulator.id }}-menu">- {% for sim_entity_class_wrapper in simulator.sim_entity_class_wrapper_list %}+ {% for sim_entity_class_data in simulator.sim_entity_class_data_list %}{% if forloop.counter > 1 %}<div class="dropdown-divider"></div>{% endif %}<a role="menuitem" class="dropdown-item plain"- href="{% url 'simulator_entity_add' simulator_id=simulator.id class_name=sim_entity_class_wrapper.name %} "+ href="{% url 'simulator_entity_add' simulator_id=simulator.id class_id=sim_entity_class_data.class_id %} "data-async="modal">- {{ sim_entity_class_wrapper.label }}+ {{ sim_entity_class_data.class_label }}</a>{% endfor %}</div>diff --git a/src/hi/simulator/transient_models.py b/src/hi/simulator/transient_models.pyindex df1790a2..52954260 100644--- a/src/hi/simulator/transient_models.py+++ b/src/hi/simulator/transient_models.py@@ -30,13 +30,6 @@ class SimState:return cls( **data )-@dataclass-class FormField:- name : str- type : Type- default : Any = None--@dataclass( frozen = True )class SimEntity:"""@@ -59,6 +52,19 @@ class SimEntity:def class_label(cls):raise NotImplementedError('Subclasses must override this method.')+ @classmethod+ def get_entity_type(cls) -> EntityType:+ raise NotImplementedError('Subclasses must override this method.')++ def get_sim_state_list(self) -> List[ SimState ]:+ """+ These are defined by the Simulator and used by the SimulatorManager to+ know what states exists and can be simulated. The Simulator keeps track of+ the current value of these states as provided by the SimulatorManager by+ way of the UI or a predefined simulation script. These are not persisted.+ """+ raise NotImplementedError('Subclasses must override this method.')+def to_json_dict(self) -> Dict[ str, Any ]:"""Subclasses only need to override this if the field types are not@@ -93,8 +99,7 @@ class SimEntity:def to_initial_form_values( self ) -> Dict[ str, Any ]:initial_values = dict()for field in fields(self):- value = getattr( self, field.name )- initial_values[field.name] = value+ initial_values[field.name] = getattr( self, field.name )continuereturn initial_values@@ -104,24 +109,11 @@ class SimEntity:for field in fields( cls ):value = form_data.get( field.name, field.default )if value is MISSING:- raise ValueError(f'Missing required field: {field.name}')+ value = Nonekwargs[field.name] = valuecontinuereturn cls( **kwargs )- @classmethod- def get_entity_type(cls) -> EntityType:- raise NotImplementedError('Subclasses must override this method.')-- def get_sim_state_list(self) -> List[ SimState ]:- """- These are defined by the Simulator and used by the SimulatorManager to- know what states exists and can be simulated. The Simulator keeps track of- the current value of these states as provided by the SimulatorManager by- way of the UI or a predefined simulation script. These are not persisted.- """- raise NotImplementedError('Subclasses must override this method.')-@dataclassclass SimEntityData:@@ -131,16 +123,16 @@ class SimEntityData:@dataclass-class SimEntityClassWrapper:+class SimEntityClassData:sim_entity_class : Type[ SimEntity ]@property- def name(self) -> str:+ def class_id(self) -> str:return f'{self.sim_entity_class.__module__}.{self.sim_entity_class.__qualname__}'@property- def label(self) -> str:+ def class_label(self) -> str:return self.sim_entity_class.class_label()@propertydiff --git a/src/hi/simulator/urls.py b/src/hi/simulator/urls.pyindex 3a7194b4..9175b968 100644--- a/src/hi/simulator/urls.py+++ b/src/hi/simulator/urls.py@@ -29,7 +29,7 @@ urlpatterns = [views.ProfileSwitchView.as_view(),name = 'simulator_profile_switch' ),- re_path( r'^entity/add/(?P<simulator_id>[\w_\-\.\:]+)/(?P<class_name>[\w\.\_]+)$',+ re_path( r'^entity/add/(?P<simulator_id>[\w_\-\.\:]+)/(?P<class_id>[\w\.\_]+)$',views.SimEntityAddView.as_view(),name = 'simulator_entity_add' ),diff --git a/src/hi/simulator/view_mixins.py b/src/hi/simulator/view_mixins.pyindex b1071f4e..acfc0561 100644--- a/src/hi/simulator/view_mixins.py+++ b/src/hi/simulator/view_mixins.py@@ -50,23 +50,19 @@ class SimulatorViewMixin:)return simulator- def get_entity_class( self, simulator : Simulator, request, *args, **kwargs ) -> Type[ SimEntity ]:- class_name = kwargs.get('class_name')- return self.get_entity_class_by_name(+ def get_entity_class_data( self, simulator : Simulator, request, *args, **kwargs ) -> Type[ SimEntity ]:+ class_id = kwargs.get('class_id')+ return self.get_entity_class_data_by_id(simulator = simulator,- class_name = class_name,+ class_id = class_id,)- def get_entity_class_by_name( self, simulator : Simulator, class_name : str ) -> Type[ SimEntity ]:- sim_entity_class = None- for sim_entity_class_wrapper in simulator.sim_entity_class_wrapper_list:- if class_name == sim_entity_class_wrapper.name:- sim_entity_class = sim_entity_class_wrapper.sim_entity_class- break+ def get_entity_class_data_by_id( self, simulator : Simulator, class_id : str ) -> Type[ SimEntity ]:+ for sim_entity_class_data in simulator.sim_entity_class_data_list:+ if class_id == sim_entity_class_data.class_id:+ return sim_entity_class_datacontinue- if not sim_entity_class:- raise Http404( 'Unknown entity class name.' )- return sim_entity_class+ raise Http404( 'Unknown entity class id.' )def get_db_sim_entity( self, request, *args, **kwargs ) -> SimProfile:db_sim_entity_id = kwargs.get('sim_entity_id')diff --git a/src/hi/simulator/views.py b/src/hi/simulator/views.pyindex 52f5af7d..d3a38fe1 100644--- a/src/hi/simulator/views.py+++ b/src/hi/simulator/views.py@@ -10,7 +10,7 @@ from .exceptions import SimEntityValidationErrorfrom . import formsfrom .models import DbSimEntityfrom .simulator_manager import SimulatorManager-from .transient_models import SimEntity, SimEntityClassWrapper+from .transient_models import SimEntity, SimEntityClassDatafrom .view_mixins import SimulatorViewMixin@@ -125,30 +125,26 @@ class SimEntityAddView( View, SimulatorViewMixin ):def get( self, request, *args, **kwargs ):simulator = self.get_simulator( request, *args, **kwargs)- sim_entity_class = self.get_entity_class( simulator, request, *args, **kwargs )- sim_entity_class_wrapper = SimEntityClassWrapper( sim_entity_class = sim_entity_class )-- sim_entity_form = forms.SimEntityForm( sim_entity_class = sim_entity_class )+ sim_entity_class_data = self.get_entity_class_data( simulator, request, *args, **kwargs )+ sim_entity_form = forms.SimEntityForm( sim_entity_class = sim_entity_class_data.sim_entity_class )context = {'simulator': simulator,- 'sim_entity_class_wrapper': sim_entity_class_wrapper,+ 'sim_entity_class_data': sim_entity_class_data,'sim_entity_form': sim_entity_form,}return render( request, self.MODAL_TEMPLATE_NAME, context )def post( self, request, *args, **kwargs ):simulator = self.get_simulator( request, *args, **kwargs)- sim_entity_class = self.get_entity_class( simulator, request, *args, **kwargs )- sim_entity_class_wrapper = SimEntityClassWrapper( sim_entity_class = sim_entity_class )-+ sim_entity_class_data = self.get_entity_class_data( simulator, request, *args, **kwargs )sim_entity_form = forms.SimEntityForm(- sim_entity_class,+ sim_entity_class_data.sim_entity_class,request.POST,)if not sim_entity_form.is_valid():context = {'simulator': simulator,- 'sim_entity_class_wrapper': sim_entity_class_wrapper,+ 'sim_entity_class_data': sim_entity_class_data,'sim_entity_form': sim_entity_form,}return render( request, self.MODAL_TEMPLATE_NAME, context )@@ -174,13 +170,13 @@ class SimEntityEditView( View, SimulatorViewMixin ):simulator = SimulatorManager().get_simulator( simulator_id = db_sim_entity.simulator_id )if not simulator:raise Http404( 'Unknown simulator id "{simulator_id}".' )- sim_entity_class = self.get_entity_class_by_name(+ sim_entity_class_data = self.get_entity_class_data_by_id(simulator = simulator,- class_name = db_sim_entity.entity_class_name,+ class_id = db_sim_entity.entity_class_id,)sim_entity = SimEntity.from_json_dict( db_sim_entity.editable_fields )sim_entity_form = forms.SimEntityForm(- sim_entity_class = sim_entity_class,+ sim_entity_class = sim_entity_class_data.sim_entity_class,initial = sim_entity.to_initial_form_values(),)context = {@@ -196,13 +192,13 @@ class SimEntityEditView( View, SimulatorViewMixin ):simulator = SimulatorManager().get_simulator( simulator_id = db_sim_entity.simulator_id )if not simulator:raise Http404( 'Unknown simulator id "{simulator_id}".' )- sim_entity_class = self.get_entity_class_by_name(+ sim_entity_class_data = self.get_entity_class_data_by_id(simulator = simulator,- class_name = db_sim_entity.entity_class_name,+ class_id = db_sim_entity.entity_class_id,)previous_sim_entity = SimEntity.from_json_dict( db_sim_entity.editable_fields )sim_entity_form = forms.SimEntityForm(- sim_entity_class,+ sim_entity_class_data.sim_entity_class,request.POST,)if not sim_entity_form.is_valid():