Files
jarvis-models/src/blackbox/calculator.py
2024-03-21 15:59:35 +08:00

42 lines
1.4 KiB
Python

from fastapi import status
from fastapi.responses import JSONResponse
from .blackbox import Blackbox
class Calculator(Blackbox):
"""This class just for example, it show how to implement Blackbox interface."""
def __call__(self, *args, **kwargs):
return self.processing(*args, **kwargs)
def valid(self, *args, **kwargs) -> bool:
data = args[0]
return isinstance(data, dict) and "op" in data and "left" in data and "right" in data
def processing(self, data: dict) -> int | float:
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)