Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
app = FastAPI()
|
| 7 |
+
|
| 8 |
+
# Path to store users (persistent across HF Spaces runs)
|
| 9 |
+
USERS_FILE = Path("users.json")
|
| 10 |
+
|
| 11 |
+
# Ensure the file exists
|
| 12 |
+
if not USERS_FILE.exists():
|
| 13 |
+
USERS_FILE.write_text("[]") # empty list
|
| 14 |
+
|
| 15 |
+
# Pydantic model for input
|
| 16 |
+
class User(BaseModel):
|
| 17 |
+
username: str
|
| 18 |
+
num1: float
|
| 19 |
+
num2: float
|
| 20 |
+
|
| 21 |
+
# Helper function to load users
|
| 22 |
+
def load_users():
|
| 23 |
+
with USERS_FILE.open("r") as f:
|
| 24 |
+
return json.load(f)
|
| 25 |
+
|
| 26 |
+
# Helper function to save users
|
| 27 |
+
def save_users(users):
|
| 28 |
+
with USERS_FILE.open("w") as f:
|
| 29 |
+
json.dump(users, f, indent=2)
|
| 30 |
+
|
| 31 |
+
# Endpoint to add user and sum numbers
|
| 32 |
+
@app.post("/add-user")
|
| 33 |
+
def add_user(user: User):
|
| 34 |
+
users = load_users()
|
| 35 |
+
|
| 36 |
+
# Check if username already exists
|
| 37 |
+
if any(u["username"] == user.username for u in users):
|
| 38 |
+
raise HTTPException(status_code=400, detail="Username already exists")
|
| 39 |
+
|
| 40 |
+
# Add user
|
| 41 |
+
users.append({
|
| 42 |
+
"username": user.username,
|
| 43 |
+
"num1": user.num1,
|
| 44 |
+
"num2": user.num2,
|
| 45 |
+
"sum": user.num1 + user.num2
|
| 46 |
+
})
|
| 47 |
+
save_users(users)
|
| 48 |
+
|
| 49 |
+
return {
|
| 50 |
+
"message": f"User {user.username} added successfully!",
|
| 51 |
+
"sum": user.num1 + user.num2
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
# Endpoint to list all users
|
| 55 |
+
@app.get("/users")
|
| 56 |
+
def get_users():
|
| 57 |
+
return load_users()
|