From 69019d432bc326f3a524f59e5638067f150e1f5d Mon Sep 17 00:00:00 2001 From: William Chiu Date: Sat, 25 Jan 2025 17:26:24 -0500 Subject: [PATCH 1/3] backend --- backend/api/endpoints/command.py | 28 +++++++++++++++++--- backend/api/middlewares/logger_middleware.py | 14 ++++++++++ backend/data/data_models.py | 13 +++++++++ 3 files changed, 51 insertions(+), 4 deletions(-) diff --git a/backend/api/endpoints/command.py b/backend/api/endpoints/command.py index 583ea5a..edc20f1 100644 --- a/backend/api/endpoints/command.py +++ b/backend/api/endpoints/command.py @@ -24,23 +24,43 @@ def get_commands(db: Session = Depends(get_db)): @command_router.post("/", response_model=CommandSingleResponse) -def create_command(payload: CommandRequest): +def create_command(payload: CommandRequest, db: Session = Depends(get_db)): """ Creates an item with the given payload in the database and returns this payload after pulling it from the database @param payload: The data used to create an item @return returns a json object with field of "data" under which there is the payload now pulled from the database """ - # TODO:(Member) Implement this endpoint - + try: + posted_command = Command(**payload.dict()) + db.add(posted_command) + db.commit() + db.refresh(posted_command) + return {"data": posted_command} + except Exception as error: + db.rollback() + raise HTTPException( + status_code = 500, + detail = str(error), + ) @command_router.delete("/{id}", response_model=CommandListResponse) -def delete_command(id: int): +def delete_command(id: int, db: Session = Depends(get_db)): """ Deletes the item with the given id if it exists. Otherwise raises a 404 error. @param id: The id of the item to delete @return returns the list of commands after deleting the item """ + DeletedCommand = db.get(Command, id) + if DeletedCommand is None: + raise HTTPException(status_code=404, detail = "Command not found") + db.delete(DeletedCommand) + db.commit() + return get_commands(db) + + + + # TODO:(Member) Implement this endpoint diff --git a/backend/api/middlewares/logger_middleware.py b/backend/api/middlewares/logger_middleware.py index 44daa5d..0b3fe7f 100644 --- a/backend/api/middlewares/logger_middleware.py +++ b/backend/api/middlewares/logger_middleware.py @@ -1,7 +1,9 @@ from collections.abc import Callable from typing import Any from fastapi import Request, Response +from ...utils.logging import logger from starlette.middleware.base import BaseHTTPMiddleware +from time import time class LoggerMiddleware(BaseHTTPMiddleware): @@ -18,5 +20,17 @@ async def dispatch( @return Response from endpoint """ # TODO:(Member) Finish implementing this method + logger.info(f"Req headers:{dict(request.headers)}") + logger.info(f"Req: {request.method} {request.url}") + try: + body = await response.json() + logger.info("Req Body: {body}") + except Exception as error: + logger.warning(f"Unable to parse Request Body. Error: {str(error)}") + startTime = time() response = await call_next(request) + executionTime = time() - startTime + logger.info(f"Response status: {response.status_code}") + logger.info(f"Response Headers: {response.headers}") + logger.info(f"Response Time:{executionTime:.2f} seconds") return response diff --git a/backend/data/data_models.py b/backend/data/data_models.py index 68adddb..f91f5c3 100644 --- a/backend/data/data_models.py +++ b/backend/data/data_models.py @@ -32,6 +32,19 @@ def validate_params_format(self): In either of these cases return self. Otherwise raise a ValueError. The format of the comma seperated values is "data1,data2" so no spaces between data and the commas. """ + params = self.params + format = self.format + if (not params and not format): + return self + elif (type(params) ==str and type(format)==str): + if(params.count(",")==format.count(",")): + return self + else: + raise ValueError(f"""Error in Params and Format. Both Params and Format must have no spaces between data with commas separating each unique value or both must be None. + The Current Params and Format are as follows: + Params: {params} + Format: {format} + """) # TODO: (Member) Implement this method return self From d7c02ea45729d4e87cd86bb96228155baba8c1ac Mon Sep 17 00:00:00 2001 From: William Chiu Date: Sat, 25 Jan 2025 17:59:18 -0500 Subject: [PATCH 2/3] Made changes --- backend/api/endpoints/command.py | 9 +++++---- backend/api/middlewares/logger_middleware.py | 2 +- backend/data/data_models.py | 7 +++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/backend/api/endpoints/command.py b/backend/api/endpoints/command.py index edc20f1..4ae14bf 100644 --- a/backend/api/endpoints/command.py +++ b/backend/api/endpoints/command.py @@ -53,12 +53,13 @@ def delete_command(id: int, db: Session = Depends(get_db)): @param id: The id of the item to delete @return returns the list of commands after deleting the item """ - DeletedCommand = db.get(Command, id) - if DeletedCommand is None: + deleted_command = db.get(Command, id) + if deleted_command is None: raise HTTPException(status_code=404, detail = "Command not found") - db.delete(DeletedCommand) + db.delete(deleted_command) db.commit() - return get_commands(db) + commands = get_commands(db) + return commands diff --git a/backend/api/middlewares/logger_middleware.py b/backend/api/middlewares/logger_middleware.py index 0b3fe7f..4bd8738 100644 --- a/backend/api/middlewares/logger_middleware.py +++ b/backend/api/middlewares/logger_middleware.py @@ -1,7 +1,7 @@ from collections.abc import Callable from typing import Any from fastapi import Request, Response -from ...utils.logging import logger +from backend.utils.logging import logger from starlette.middleware.base import BaseHTTPMiddleware from time import time diff --git a/backend/data/data_models.py b/backend/data/data_models.py index f91f5c3..2558fab 100644 --- a/backend/data/data_models.py +++ b/backend/data/data_models.py @@ -34,11 +34,10 @@ def validate_params_format(self): """ params = self.params format = self.format - if (not params and not format): + if self.format is None and self.params is None: + return self + elif (isinstance(params, str) and isinstance(format, str) and params.count(",")==format.count(",")): return self - elif (type(params) ==str and type(format)==str): - if(params.count(",")==format.count(",")): - return self else: raise ValueError(f"""Error in Params and Format. Both Params and Format must have no spaces between data with commas separating each unique value or both must be None. The Current Params and Format are as follows: From 0180bb7046457d443dd2d5599a9f5e023a360220 Mon Sep 17 00:00:00 2001 From: William Chiu Date: Sun, 26 Jan 2025 12:23:22 -0500 Subject: [PATCH 3/3] made changes --- backend/api/endpoints/command.py | 5 +++-- backend/data/data_models.py | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/backend/api/endpoints/command.py b/backend/api/endpoints/command.py index 4ae14bf..3ea70e5 100644 --- a/backend/api/endpoints/command.py +++ b/backend/api/endpoints/command.py @@ -58,8 +58,9 @@ def delete_command(id: int, db: Session = Depends(get_db)): raise HTTPException(status_code=404, detail = "Command not found") db.delete(deleted_command) db.commit() - commands = get_commands(db) - return commands + query = select(Command) + items = db.exec(query).all() + return {"data": items} diff --git a/backend/data/data_models.py b/backend/data/data_models.py index 2558fab..b9a42f4 100644 --- a/backend/data/data_models.py +++ b/backend/data/data_models.py @@ -36,7 +36,7 @@ def validate_params_format(self): format = self.format if self.format is None and self.params is None: return self - elif (isinstance(params, str) and isinstance(format, str) and params.count(",")==format.count(",")): + elif isinstance(params, str) and isinstance(format, str) and params.count(",")==format.count(","): return self else: raise ValueError(f"""Error in Params and Format. Both Params and Format must have no spaces between data with commas separating each unique value or both must be None.