from fastapi import APIRouter, HTTPException import logging import db from pydantic import BaseModel #Logging logging.basicConfig( filename='api.log', # Log to a file level=logging.DEBUG, # Log everything (DEBUG and above) format='%(asctime)s %(levelname)s %(message)s' ) logging.info('Application started') try: logging.debug('Debug info here') except Exception as e: logging.exception('An error occurred') router = APIRouter(prefix="/db", tags=["db"]) @router.get("/help") def get_help(): return {"name of clothes": "example", "weight": "sample weight (only floats)", "pieces": "sample pieces (only ints)"} class Item_name(BaseModel): name_of_clothes: str class Config: fields = { "name_of_clothes": "name of clothes" } class Item_weight(BaseModel): weight: float class Item_piece(BaseModel): pieces: int @router.post("/insert", status_code=201) def insert(item_name: Item_name, item_weight: Item_weight, item_pieces: Item_piece): name = item_name.name_of_clothes.upper() weight = item_weight.weight pieces = item_pieces.pieces db.new_part(name, weight, pieces) logging.info("new Item created in DB") return {"message": "Item inserted"} @router.put("/update/{clothe_name}/pieces", status_code=202) def update_pieces(clothe_name: str, item_pieces: Item_piece): name = clothe_name.upper() pieces = item_pieces.pieces if db.check_clothe(name) != None: db.update_pieces(name, pieces) logging.info(f"Item {name} was set a new count") return {"message": "pieces updated"} else: logging.error(f"Item {name} not found") raise HTTPException(status_code=404, detail=f"Item {name} not found") @router.put("/update/{clothe_name}/weight", status_code=202) def update_weight(clothe_name: str, item: Item_weight): name = clothe_name.upper() weight = item.weight if db.check_clothe(name) != None: db.update_weight(name, weight) logging.info(f"Item {name} was set a new weight") return {"message": "weight updated"} else: logging.error(f"Item {name} not found") raise HTTPException(status_code=404, detail=f"Item {name} not found") @router.delete("/{clothe_name}/delete", status_code=204) def delete(clothe_name: str): name = clothe_name.upper() if db.check_clothe(name) != None: db.delete(name) logging.critical(f"Item {name} was deleted") return {"message": "Item was deleted"} else: logging.error(f"Item {name} not found") raise HTTPException(status_code=404, detail=f"Item {name} not found")