from fastapi import status from fastapi.responses import JSONResponse from blackbox.blackbox import Blackbox class Calculator(Blackbox): """This class just for example, it show how to implement Blackbox interface.""" def valid(self, data: any) -> bool: return isinstance(data, dict) and "op" in data and "left" in data and "right" in data def processing(self, data: dict) -> any: if not self.valid(data): raise ValueError("Invalid data") a = data["left"] b = data["right"] op = data["op"] if op == "add": return a + b if op == "sub": return a - b if op == "mul": return a * b if op == "div": return a / b raise ValueError("Invalid operation") async def fast_api_handler(self, request) -> any: try: data = await request.json() except: return JSONResponse(content={"error": "json parse error"}, status_code=status.HTTP_400_BAD_REQUEST) try: result = self.processing(data) except ValueError as e: return JSONResponse(content={"error": str(e)}, status_code=status.HTTP_400_BAD_REQUEST) return JSONResponse(content={"result": result}, status_code=status.HTTP_200_OK)