Skip to content

Commit

Permalink
Merge pull request #31 from fioreale/24-exercises-description-improve…
Browse files Browse the repository at this point in the history
…ment

24 exercises description improvement
  • Loading branch information
fioreale authored Jun 1, 2024
2 parents 668f740 + 87c68b1 commit 24acfb2
Show file tree
Hide file tree
Showing 9 changed files with 252 additions and 438 deletions.
24 changes: 12 additions & 12 deletions app/api/db/volume.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,20 @@
from pathlib import Path
from typing import List, Optional

from ..model import Scheda, Workout
from ..models import Scheda, Workout

# Define the directory where workout files will be stored
DATA_DIR = Path("/data") # Update this path as needed


def get_workout_file_path(name: str) -> Path:
def generate_workout_file_path(name: str) -> Path:
"""Generate a file path for a given workout name."""
return DATA_DIR / f"{name}.json"


def getWorkout(name: str) -> Optional[dict]:
def read_workout_from_json(name: str) -> Optional[dict]:
"""Retrieve a workout from a JSON file."""
file_path = get_workout_file_path(name)
file_path = generate_workout_file_path(name)
try:
if file_path.exists():
with file_path.open("r") as file:
Expand All @@ -26,7 +26,7 @@ def getWorkout(name: str) -> Optional[dict]:
return None


def getWorkoutList() -> List[str]:
def list_all_workouts() -> List[str]:
"""List all workouts by scanning the data directory for JSON files."""
try:
return [f.stem for f in DATA_DIR.glob("*.json")]
Expand All @@ -35,9 +35,9 @@ def getWorkoutList() -> List[str]:
return []


def loadWorkout(workout: Workout) -> bool:
def save_workout_to_json(workout: Workout) -> bool:
"""Save a workout to a JSON file."""
file_path = get_workout_file_path(workout.name)
file_path = generate_workout_file_path(workout.name)
try:
with file_path.open("w") as file:
json.dump(workout.model_dump(), file)
Expand All @@ -47,9 +47,9 @@ def loadWorkout(workout: Workout) -> bool:
return False


def updateWorkout(name: str, scheda: Scheda) -> bool:
def update_workout_in_json(name: str, scheda: Scheda) -> bool:
"""Update a workout by modifying its JSON file."""
workout_data = getWorkout(name)
workout_data = read_workout_from_json(name)
try:
if workout_data:
workout_obj = Workout(**workout_data)
Expand All @@ -58,7 +58,7 @@ def updateWorkout(name: str, scheda: Scheda) -> bool:
if s.name == scheda.name:
workout_obj.schede[idx] = scheda

if loadWorkout(workout_obj):
if save_workout_to_json(workout_obj):
return True
else:
logging.error(
Expand All @@ -73,9 +73,9 @@ def updateWorkout(name: str, scheda: Scheda) -> bool:
return False


def deleteWorkout(name: str) -> bool:
def delete_workout_file(name: str) -> bool:
"""Delete a workout's JSON file."""
file_path = get_workout_file_path(name)
file_path = generate_workout_file_path(name)
try:
file_path.unlink(missing_ok=True)
return True
Expand Down
21 changes: 12 additions & 9 deletions app/api/endpoints.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@

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

from app.api.db.volume import (deleteWorkout, getWorkout, getWorkoutList,
loadWorkout, updateWorkout)

from app.api.db.volume import (
delete_workout_file,
read_workout_from_json,
list_all_workouts,
save_workout_to_json,
update_workout_in_json,
)
from .models import Scheda, Workout

router = APIRouter()
Expand All @@ -18,7 +21,7 @@ async def get_workout(name: str):
raise HTTPException(status_code=400, detail="Name parameter cannot be empty")

try:
workout_db = getWorkout(name)
workout_db = read_workout_from_json(name)

if workout_db is not None:
workout_data = Workout(**workout_db)
Expand All @@ -36,7 +39,7 @@ async def delete_workout(name: str):
raise HTTPException(status_code=400, detail="Name parameter cannot be empty")

try:
res = deleteWorkout(name)
res = delete_workout_file(name)

if res:
return JSONResponse(status_code=200, content={"message": "Workout deleted"})
Expand All @@ -51,7 +54,7 @@ async def delete_workout(name: str):
@router.get("/workout")
async def get_workout_list():
try:
workout_list_data = getWorkoutList()
workout_list_data = list_all_workouts()

return workout_list_data
except ValidationError as e:
Expand All @@ -61,7 +64,7 @@ async def get_workout_list():
@router.post("/workout")
async def load_workout(workout: Workout):
try:
if loadWorkout(workout):
if save_workout_to_json(workout):
return JSONResponse(
status_code=200, content={"message": "Workout upload successful"}
)
Expand All @@ -76,7 +79,7 @@ async def load_workout(workout: Workout):
@router.patch("/workout/{name}")
async def update_workout(name: str, scheda: Scheda):
try:
if updateWorkout(name, scheda):
if update_workout_in_json(name, scheda):
return JSONResponse(
status_code=200, content={"message": "Workout upload successful"}
)
Expand Down
91 changes: 0 additions & 91 deletions app/db/workout_db.py

This file was deleted.

89 changes: 3 additions & 86 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
import json

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

from .api.models import Scheda, Workout
from .db.workout_db import (deleteWorkout, getWorkoutDB, getWorkoutList,
loadWorkoutDB, updateWorkout)
from .api.endpoints import router

app = FastAPI()
app.include_router(router)


@app.exception_handler(RequestValidationError)
Expand All @@ -22,84 +17,6 @@ async def validation_exception_handler(request, exc):
)


@app.get("/workout/{name}")
async def get_workout(name: str):
if not name:
raise HTTPException(status_code=400, detail="Name parameter cannot be empty")

try:
workout_db = getWorkoutDB(name)

if workout_db is not None:
workout_dict = json.loads(workout_db.get("data"))

workout_data = Workout(**workout_dict)

return workout_data
else:
raise HTTPException(status_code=400, detail="No workout to load")
except ValidationError as e:
raise RequestValidationError(errors=e.errors())


@app.delete("/workout/{name}")
async def delete_workout(name: str):
if not name:
raise HTTPException(status_code=400, detail="Name parameter cannot be empty")

try:
res = deleteWorkout(name)

if res:
return JSONResponse(status_code=200, content={"message": "Workout deleted"})
else:
return JSONResponse(
status_code=500, content={"message": "Cannot delete workout"}
)
except ValidationError as e:
raise RequestValidationError(errors=e.errors())


@app.get("/workout")
async def get_workout_list():
try:
workout_list_data = getWorkoutList()

return workout_list_data
except ValidationError as e:
raise RequestValidationError(errors=e.errors())


@app.post("/workout")
async def load_workout(workout: Workout):
try:
if loadWorkoutDB(workout):
return JSONResponse(
status_code=200, content={"message": "Workout upload successful"}
)
else:
return JSONResponse(
status_code=500, content={"message": "Cannot upload workout"}
)
except ValidationError as e:
raise RequestValidationError(errors=e.errors())


@app.patch("/workout/{name}")
async def update_workout(name: str, scheda: Scheda):
try:
if updateWorkout(name, scheda):
return JSONResponse(
status_code=200, content={"message": "Workout upload successful"}
)
else:
return JSONResponse(
status_code=500, content={"message": "Cannot upload workout"}
)
except ValidationError as e:
raise RequestValidationError(errors=e.errors())


app.mount("/", StaticFiles(directory="app/public", html=True))

if __name__ == "__main__":
Expand Down
Loading

0 comments on commit 24acfb2

Please sign in to comment.