fix: rename

This commit is contained in:
Dan Chen
2024-03-18 17:58:23 +08:00
parent f6dd6159a8
commit 2612d5d370
4 changed files with 59 additions and 18 deletions

View 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)