legacy_migration_utils.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """
  2. This module is part of our data model migration (see https://github.com/SeitaBV/flexmeasures/projects/9).
  3. It will become obsolete when Assets, Markets and WeatherSensors can no longer be initialized.
  4. """
  5. from __future__ import annotations
  6. from datetime import datetime
  7. from flexmeasures.data import db
  8. def copy_old_sensor_attributes(
  9. old_sensor,
  10. old_sensor_type_attributes: list[str],
  11. old_sensor_attributes: list[str],
  12. old_sensor_type: "AssetType | MarketType | WeatherSensorType" = None, # noqa F821
  13. ) -> dict:
  14. """
  15. :param old_sensor: an Asset, Market or WeatherSensor instance
  16. :param old_sensor_type_attributes: names of attributes of the old sensor's type that should be copied
  17. :param old_sensor_attributes: names of attributes of the old sensor that should be copied
  18. :param old_sensor_type: the old sensor's type
  19. :returns: dictionary containing an "attributes" dictionary with attribute names and values
  20. """
  21. new_model_attributes_from_old_sensor_type = {
  22. a: getattr(old_sensor_type, a) for a in old_sensor_type_attributes
  23. }
  24. new_model_attributes_from_old_sensor = {
  25. a: (
  26. getattr(old_sensor, a)
  27. if not isinstance(getattr(old_sensor, a), datetime)
  28. else getattr(old_sensor, a).isoformat()
  29. )
  30. for a in old_sensor_attributes
  31. }
  32. return dict(
  33. attributes={
  34. **new_model_attributes_from_old_sensor_type,
  35. **new_model_attributes_from_old_sensor,
  36. }
  37. )
  38. def get_old_model_type(
  39. kwargs: dict,
  40. old_sensor_type_class: "Type[AssetType | MarketType | WeatherSensorType]", # noqa F821
  41. old_sensor_type_name_key: str,
  42. old_sensor_type_key: str,
  43. ) -> "AssetType | MarketType | WeatherSensorType": # noqa F821
  44. """
  45. :param kwargs: keyword arguments used to initialize a new Asset, Market or WeatherSensor
  46. :param old_sensor_type_class: AssetType, MarketType, or WeatherSensorType
  47. :param old_sensor_type_name_key: "asset_type_name", "market_type_name", or "weather_sensor_type_name"
  48. :param old_sensor_type_key: "asset_type", "market_type", or "sensor_type" (instead of "weather_sensor_type"),
  49. i.e. the name of the class attribute for the db.relationship to the type's class
  50. :returns: the old sensor's type
  51. """
  52. if old_sensor_type_name_key in kwargs:
  53. old_sensor_type = db.session.get(
  54. old_sensor_type_class, kwargs[old_sensor_type_name_key]
  55. )
  56. else:
  57. old_sensor_type = kwargs[old_sensor_type_key]
  58. return old_sensor_type