-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator.py
More file actions
78 lines (62 loc) · 2.04 KB
/
calculator.py
File metadata and controls
78 lines (62 loc) · 2.04 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
import uvicorn
import ast
import operator as op
app = FastAPI(title="Modern Calculator API", description="A simple calculator API with a modern UI", version="1.0")
# Serve the modern calculator UI from the static/ folder
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/")
async def root():
return RedirectResponse(url="/static/index.html")
# Minimal, safe expression evaluator using ast
operators = {
ast.Add: op.add,
ast.Sub: op.sub,
ast.Mult: op.mul,
ast.Div: op.truediv,
ast.Pow: op.pow,
ast.Mod: op.mod,
ast.FloorDiv: op.floordiv,
}
def eval_node(node):
if isinstance(node, ast.Expression):
return eval_node(node.body)
if isinstance(node, ast.BinOp):
left = eval_node(node.left)
right = eval_node(node.right)
op_type = type(node.op)
if op_type in operators:
return operators[op_type](left, right)
raise ValueError("Unsupported operator")
if isinstance(node, ast.UnaryOp):
if isinstance(node.op, ast.UAdd):
return +eval_node(node.operand)
if isinstance(node.op, ast.USub):
return -eval_node(node.operand)
raise ValueError("Unsupported unary operator")
if isinstance(node, ast.Num):
return node.n
if isinstance(node, ast.Constant):
if isinstance(node.value, (int, float)):
return node.value
raise ValueError("Unsupported constant")
raise ValueError("Unsupported expression")
def safe_eval(expr: str):
parsed = ast.parse(expr, mode="eval")
return eval_node(parsed)
class CalcRequest(BaseModel):
expression: str
@app.post("/api/calc")
async def calculate(req: CalcRequest):
expr = req.expression.strip()
try:
result = safe_eval(expr)
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=400)
return {"result": result, "expression": expr}
if __name__ == "__main__":
# Run with: uvicorn calculator:app --reload
print("calculator FastAPI app. Run with: uvicorn calculator:app --reload")