generic_assets.py 815 B

12345678910111213141516171819202122232425
  1. from __future__ import annotations
  2. from flask import abort
  3. from marshmallow import fields
  4. from sqlalchemy import select
  5. from flexmeasures.data import db
  6. from flexmeasures.data.models.generic_assets import GenericAsset
  7. class AssetIdField(fields.Integer):
  8. """
  9. Field that represents a generic asset ID. It de-serializes from the asset id to an asset instance.
  10. """
  11. def _deserialize(self, asset_id: int, attr, obj, **kwargs) -> GenericAsset:
  12. asset: GenericAsset = db.session.execute(
  13. select(GenericAsset).filter_by(id=int(asset_id))
  14. ).scalar_one_or_none()
  15. if asset is None:
  16. raise abort(404, f"GenericAsset {asset_id} not found")
  17. return asset
  18. def _serialize(self, asset: GenericAsset, attr, data, **kwargs) -> int:
  19. return asset.id