Implement record fetching from database

This commit is contained in:
linuskmr 2021-12-25 18:59:36 +01:00
parent 113d35201b
commit 96573e7d48

View file

@ -1,67 +1,92 @@
import logging
from datetime import datetime, timedelta
from fastapi import APIRouter, status, Path
from src.models.record import RecordStartCreate, RecordRead, RecordCreate
from fastapi import APIRouter, status, Path, Depends, HTTPException
from sqlmodel import select, Session
from src import database
from src.models.record import Record, RecordRead, RecordCreate
router = APIRouter(prefix="/records", tags=["Records"])
@router.get("/", response_model=list[RecordRead], summary="Get a list of all records")
async def all_tags() -> list[RecordRead]:
async def all_records(
*,
session: Session = Depends(database.get_session)
) -> list[RecordRead]:
"""Returns a list of all records."""
return [
RecordRead(
start=datetime.now() - timedelta(hours=3),
end=datetime.now(),
project="Uni",
tags=["Listening Lectures", "Not be concentrated"]
),
RecordRead(
start=datetime.now() - timedelta(hours=7),
end=datetime.now() - timedelta(hours=4),
project="Uni",
tags=["Listening Lectures", "Not be concentrated"]
)
]
records = session.exec(select(Record)).all()
return records
@router.post("/start", status_code=status.HTTP_201_CREATED, summary="Start a record")
async def start_record(record: RecordStartCreate):
@router.post("/start", status_code=status.HTTP_201_CREATED)
async def add_record(
*,
record: RecordCreate,
session: Session = Depends(database.get_session)
):
"""Start a record."""
print('starting record', record)
db_record = Record.from_orm(record)
session.add(db_record)
session.commit()
session.refresh(db_record)
return db_record
@router.post("/end", status_code=status.HTTP_204_NO_CONTENT, summary="End a record")
async def end_record(record: RecordStartCreate):
"""End a record."""
print('end record', record)
@router.get("/{id}", response_model=RecordRead, summary="Get a record by id")
async def get_record(id: str = Path(..., title="ID of the record")) -> RecordRead:
@router.get("/{id}", response_model=RecordRead)
async def get_record(
*,
id: str = Path(..., title="ID of the record"),
session: Session = Depends(database.get_session)
) -> Record:
"""Fetch a record by id."""
return RecordRead(
start=datetime.now() - timedelta(hours=3),
end=datetime.now(),
project="Uni",
tags=["Listening Lectures", "Not be concentrated"]
)
record = session.get(Record, id)
if not record:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
return record
@router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT, summary="Delete a record by id")
async def delete_record(id: str = Path(..., title="ID of the record")):
"""Delete a tag specified by name."""
@router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_record(
*,
id: str = Path(..., title="ID of the record"),
session: Session = Depends(database.get_session)
):
"""Delete a record specified by id."""
logging.debug(f"Deleting record {id}")
record = session.get(Record, id)
if not record:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
session.delete(record)
session.commit()
# TODO: This method implicitly returns None, which will be converted to null by FastAPI, which triggers a
# warning, because the method returns with header HTTP_204_NO_CONTENT, but has content
@router.patch("/{id}", summary="Apply partial updates to a record by id")
async def patch_record(record: RecordCreate, id: str = Path(..., title="ID of the record")):
async def patch_record(
*,
record: RecordCreate,
id: str = Path(..., title="ID of the record"),
session: Session = Depends(database.get_session)
):
"""Apply partial updates to a record."""
logging.debug(f"Patching record {id} with {record}")
# Fetch record by id from database
db_record = session.get(Record, id)
if not db_record:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
# Set all provided arguments in the database record
for key, value in record.dict(exclude_unset=True).items():
setattr(db_record, key, value)
# Write modified record to database
session.add(db_record)
session.commit()
session.refresh(db_record)
return db_record