51 lines
1.3 KiB
Python
51 lines
1.3 KiB
Python
|
|
from typing import Annotated
|
|
|
|
from fastapi import Path, HTTPException
|
|
from sqlalchemy import select
|
|
|
|
|
|
def make_primary_annotation(name=str):
|
|
return Annotated[str, Path(description=f'{name}, either id (int) or name')]
|
|
|
|
|
|
def get_single_record(session, cls, primary: str):
|
|
print(session)
|
|
print(cls)
|
|
print(primary)
|
|
result = session.get(cls, primary)
|
|
print(result)
|
|
if result is None:
|
|
result = session.scalar(select(cls).where(cls.name == primary))
|
|
if result is None:
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail=f"{cls.__class__.__name__} {primary!r} not found.")
|
|
return result
|
|
|
|
|
|
def set_item_status(session, current_user, item, status: str):
|
|
item.status_id = status
|
|
item._user__id = current_user.id
|
|
session.commit()
|
|
session.refresh(item)
|
|
return item
|
|
|
|
|
|
def update_item(session, current_user, item, data):
|
|
for k, v in data.model_dump(exclude_unset=True).items():
|
|
setattr(item, k, v)
|
|
item._user__id = current_user.id
|
|
session.commit()
|
|
session.refresh(item)
|
|
return item
|
|
|
|
|
|
def create_item(session, cls, current_user, data):
|
|
item = cls(**data.model_dump())
|
|
item._user__id = current_user.id
|
|
session.add(item)
|
|
session.commit()
|
|
session.refresh(item)
|
|
return item
|