Spaces:
Sleeping
Sleeping
| 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 | |
| def perform_calculation(request: CalculationRequest): | |
| result = calculate(request.operation, request.num1, request.num2) | |
| return {"result": result} | |