Skip to content

Commit

Permalink
More idiomatic errors for FastAPI
Browse files Browse the repository at this point in the history
  • Loading branch information
scosman committed Oct 8, 2024
1 parent ce66ea8 commit d365527
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 23 deletions.
10 changes: 9 additions & 1 deletion libs/studio/kiln_studio/custom_errors.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from fastapi import FastAPI, Request, status
from fastapi import FastAPI, HTTPException, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import ValidationError
Expand Down Expand Up @@ -49,3 +49,11 @@ async def validation_exception_handler(
"source_errors": exc.errors(),
},
)

# Wrap in a format that the client can understand (message, and error_messages)
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
return JSONResponse(
status_code=exc.status_code,
content={"message": exc.detail},
)
9 changes: 3 additions & 6 deletions libs/studio/kiln_studio/project_management.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import os
from pathlib import Path

from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi import FastAPI, HTTPException

from libs.core.kiln_ai.datamodel import Project
from libs.core.kiln_ai.utils.config import Config
Expand All @@ -17,11 +16,9 @@ def connect_project_management(app: FastAPI):
async def create_project(project: Project):
project_path = os.path.join(default_project_path(), project.name)
if os.path.exists(project_path):
return JSONResponse(
raise HTTPException(
status_code=400,
content={
"message": "Project with this name already exists. Please choose a different name."
},
detail="Project with this name already exists. Please choose a different name.",
)

os.makedirs(project_path)
Expand Down
23 changes: 7 additions & 16 deletions libs/studio/kiln_studio/task_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@
from pathlib import Path
from typing import Any, Dict

from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import ValidationError
from fastapi import FastAPI, HTTPException

from libs.core.kiln_ai.datamodel import Project, Task

Expand All @@ -14,32 +11,26 @@ def connect_task_management(app: FastAPI):
@app.post("/api/task")
async def create_task(task_data: Dict[str, Any], project_path: str | None = None):
if project_path is None or not os.path.exists(project_path):
return JSONResponse(
raise HTTPException(
status_code=400,
content={
"message": "Parent project not found. Can't create task.",
},
detail="Parent project not found. Can't create task.",
)

try:
parent_project = Project.load_from_file(Path(project_path))
except Exception as e:
return JSONResponse(
raise HTTPException(
status_code=500,
content={
"message": f"Failed to load parent project: {e}",
},
detail=f"Failed to load parent project: {e}",
)

task = Task.validate_and_save_with_subrelations(
task_data, parent=parent_project
)
if task is None:
return JSONResponse(
raise HTTPException(
status_code=400,
content={
"message": "Failed to create task.",
},
detail="Failed to create task.",
)

returnTask = task.model_dump()
Expand Down
2 changes: 2 additions & 0 deletions libs/studio/kiln_studio/test_project_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from libs.core.kiln_ai.datamodel import Project
from libs.core.kiln_ai.utils.config import Config
from libs.studio.kiln_studio.custom_errors import connect_custom_errors
from libs.studio.kiln_studio.project_management import (
connect_project_management,
default_project_path,
Expand All @@ -18,6 +19,7 @@
def app():
app = FastAPI()
connect_project_management(app)
connect_custom_errors(app)
return app


Expand Down
2 changes: 2 additions & 0 deletions libs/studio/kiln_studio/test_task_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@
from fastapi.testclient import TestClient

from libs.core.kiln_ai.datamodel import Project, Task
from libs.studio.kiln_studio.custom_errors import connect_custom_errors
from libs.studio.kiln_studio.task_management import connect_task_management


@pytest.fixture
def app():
app = FastAPI()
connect_task_management(app)
connect_custom_errors(app)
return app


Expand Down

0 comments on commit d365527

Please sign in to comment.