sources.py 866 B

12345678910111213141516171819202122232425
  1. from marshmallow import fields
  2. from flexmeasures.data import db
  3. from flexmeasures.data.models.data_sources import DataSource
  4. from flexmeasures.data.schemas.utils import (
  5. with_appcontext_if_needed,
  6. FMValidationError,
  7. MarshmallowClickMixin,
  8. )
  9. class DataSourceIdField(fields.Int, MarshmallowClickMixin):
  10. """Field that deserializes to a DataSource and serializes back to an integer."""
  11. @with_appcontext_if_needed()
  12. def _deserialize(self, value, attr, obj, **kwargs) -> DataSource:
  13. """Turn a source id into a DataSource."""
  14. source = db.session.get(DataSource, value)
  15. if source is None:
  16. raise FMValidationError(f"No data source found with id {value}.")
  17. return source
  18. def _serialize(self, source, attr, data, **kwargs):
  19. """Turn a DataSource into a source id."""
  20. return source.id