fastapi-stats / main.py
Krrrrish's picture
Update main.py
4a03be1 verified
Raw History Blame Contribute Delete
1.74 kB
import time
import uuid
from fastapi import FastAPI, HTTPException, Request, Response
app = FastAPI()
ALLOWED_ORIGIN = "https://dash-4ek5uj.example.com"
@app.middleware("http")
async def cors_and_headers(request: Request, call_next):
start = time.perf_counter()
origin = request.headers.get("origin")
# Handle CORS preflight
if request.method == "OPTIONS":
response = Response(status_code=200)
else:
response = await call_next(request)
# Allow only the assigned origin
if origin == ALLOWED_ORIGIN:
response.headers["Access-Control-Allow-Origin"] = ALLOWED_ORIGIN
response.headers["Access-Control-Allow-Methods"] = "GET, OPTIONS"
response.headers["Access-Control-Allow-Headers"] = "*"
response.headers["Vary"] = "Origin"
# Required headers on every response
response.headers["X-Request-ID"] = str(uuid.uuid4())
response.headers["X-Process-Time"] = f"{time.perf_counter() - start:.6f}"
return response
@app.get("/")
def home():
return {"message": "FastAPI Stats API is running."}
@app.get("/stats")
def stats(values: str):
try:
numbers = [int(x.strip()) for x in values.split(",") if x.strip()]
except ValueError:
raise HTTPException(
status_code=400,
detail="Values must be comma-separated integers."
)
if not numbers:
raise HTTPException(
status_code=400,
detail="No values provided."
)
total = sum(numbers)
return {
"email": "24f3005189@ds.study.iitm.ac.in",
"count": len(numbers),
"sum": total,
"min": min(numbers),
"max": max(numbers),
"mean": total / len(numbers),
}