utils.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from uuid import UUID
  2. from fastapi import HTTPException
  3. from sqlalchemy import select
  4. from sqlalchemy.orm import Session
  5. from sqlalchemy.sql import func
  6. async def verify_id_list(
  7. session: Session,
  8. id_list: list[UUID],
  9. project_id: UUID,
  10. ObjectClass,
  11. error_message: str = "Invalid id list",
  12. ) -> None:
  13. """Verfiy the list of uuids exists and are from the right project
  14. ---
  15. Parameters
  16. - session : sqlachlemy Async session to use to verify slot validity
  17. - id_list : list of id to check
  18. - project_id :
  19. - ObjectClass : the ORM class of the object to check the ids from. Need to have id and project_id property
  20. ---
  21. Raise
  22. HTTPException(400, error_message) - if all the ids doesn't exists or are not associated with the right project
  23. """
  24. statement = select(func.count(ObjectClass.id)).where(
  25. ObjectClass.id.in_(id_list) & (ObjectClass.project_id == project_id)
  26. )
  27. results = session.execute(statement)
  28. if results.scalar() != len(id_list):
  29. raise HTTPException(status_code=400, detail=error_message)
  30. def update_object_from_payload(obj, payload: dict):
  31. """Update the ORM model object from a pydantic payload dictionary"""
  32. for attr_name, value in payload.items():
  33. setattr(obj, attr_name, value)