Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions backend/api/endpoints/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,23 +24,35 @@ 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

command = Command(**payload.dict())
db.add(command)
db.commit()
db.refresh(command)
return {"data": command}




@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
"""
# TODO:(Member) Implement this endpoint
command = db.get(Command, id)
if not command:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use command is None here

raise HTTPException(status_code=404, detail="Command not found")
db.delete(command)
db.commit()
items = db.exec(select(Command)).all()
return {"data": items}
23 changes: 23 additions & 0 deletions backend/api/middlewares/logger_middleware.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
from time import perf_counter
from datetime import datetime
from collections.abc import Callable
from typing import Any
from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware

from logging import getLogger
custom_logger = getLogger("my_logger")


class LoggerMiddleware(BaseHTTPMiddleware):
async def dispatch(
Expand All @@ -18,5 +23,23 @@ async def dispatch(
@return Response from endpoint
"""
# TODO:(Member) Finish implementing this method
start_time = perf_counter()

timestamp = datetime.utcnow().isoformat()

# Log incoming request
custom_logger.info(f"[{timestamp}] Incoming request: {request.method} {request.url}")
custom_logger.info(f"Headers: {dict(request.headers)}")
if request.query_params:
custom_logger.info(f"Query Params: {dict(request.query_params)}")

# Process request
response = await call_next(request)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Print the response body as well


# Measure execution time
duration = perf_counter() - start_time
custom_logger.info(
f"Response status: {response.status_code} | Duration: {duration:.4f} seconds"
)

return response
15 changes: 14 additions & 1 deletion backend/data/data_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class MainCommand(BaseSQLModel, table=True):
data_size: int
total_size: int


@model_validator(mode="after")
def validate_params_format(self):
"""
Expand All @@ -33,7 +34,19 @@ def validate_params_format(self):
The format of the comma seperated values is "data1,data2" so no spaces between data and the commas.
"""
# TODO: (Member) Implement this method
return self
if self.params is None and self.format is None:
return self
if self.params is None or self.format is None:
raise ValueError("Both params and format should be None or both should be provided.")

params_count = len(self.params.split(","))
format_count = len(self.format.split(","))

if params_count != format_count:
raise ValueError(f"Mismatch: params has {params_count} values, but format has {format_count}.")

return self #if all checks pass return the instance



class Command(BaseSQLModel, table=True):
Expand Down
Loading