mirror of
https://github.com/BoardWare-Genius/jarvis-models.git
synced 2025-12-14 09:03:25 +00:00
fix: rename
This commit is contained in:
38
src/blackbox/calculator.py
Normal file
38
src/blackbox/calculator.py
Normal file
@ -0,0 +1,38 @@
|
||||
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 "operation" in data and "a" in data and "b" in data
|
||||
|
||||
def processing(self, data: dict) -> any:
|
||||
if not self.valid(data):
|
||||
raise ValueError("Invalid data")
|
||||
a = data["a"]
|
||||
b = data["b"]
|
||||
op = data["operation"]
|
||||
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)
|
||||
Reference in New Issue
Block a user