Spaces:
Sleeping
Sleeping
File size: 1,200 Bytes
6be1e82 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from enum import Enum
# Initialize the FastAPI app
app = FastAPI()
# Define allowed operations using Enum for better validation
class Operation(str, Enum):
add = "+"
subtract = "-"
multiply = "*"
divide = "/"
# Define the request model for the calculator
class CalculationRequest(BaseModel):
operation: Operation # Operation can be '+', '-', '*', '/'
num1: float
num2: float
# Calculator logic function
def calculate(operation: str, num1: float, num2: float):
if operation == '+':
return num1 + num2
elif operation == '-':
return num1 - num2
elif operation == '*':
return num1 * num2
elif operation == '/':
if num2 == 0:
raise HTTPException(status_code=400, detail="Division by zero is not allowed")
return num1 / num2
else:
raise HTTPException(status_code=400, detail="Invalid operation")
# Define the POST endpoint for calculations
@app.post("/calculate")
def perform_calculation(request: CalculationRequest):
result = calculate(request.operation, request.num1, request.num2)
return {"result": result}
|