Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- main.py +52 -0
- requirements.txt +3 -0
main.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from fastapi.responses import JSONResponse
|
| 3 |
+
import time
|
| 4 |
+
import psutil
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
app = FastAPI()
|
| 8 |
+
|
| 9 |
+
process = psutil.Process(os.getpid())
|
| 10 |
+
last_cpu_times = process.cpu_times()
|
| 11 |
+
last_time = time.time()
|
| 12 |
+
|
| 13 |
+
def get_cpu_percent():
|
| 14 |
+
|
| 15 |
+
global last_cpu_times, last_time
|
| 16 |
+
now = time.time()
|
| 17 |
+
times = process.cpu_times()
|
| 18 |
+
elapsed = now - last_time
|
| 19 |
+
cpu_used = (times.user - last_cpu_times.user) + (times.system - last_cpu_times.system)
|
| 20 |
+
last_cpu_times = times
|
| 21 |
+
last_time = now
|
| 22 |
+
|
| 23 |
+
return round((cpu_used / elapsed) * 100, 1)
|
| 24 |
+
|
| 25 |
+
def simulate_work():
|
| 26 |
+
|
| 27 |
+
start = time.time()
|
| 28 |
+
while (time.time() - start) < 0.005:
|
| 29 |
+
pass
|
| 30 |
+
|
| 31 |
+
@app.get("/")
|
| 32 |
+
async def root():
|
| 33 |
+
simulate_work()
|
| 34 |
+
return {"ok": True, "time": int(time.time() * 1000)}
|
| 35 |
+
|
| 36 |
+
@app.get("/metrics")
|
| 37 |
+
async def metrics():
|
| 38 |
+
try:
|
| 39 |
+
cpu_percent = get_cpu_percent()
|
| 40 |
+
mem_info = process.memory_info()
|
| 41 |
+
return {
|
| 42 |
+
"cpu": cpu_percent,
|
| 43 |
+
"memory": round(mem_info.rss / 1024 / 1024, 1)
|
| 44 |
+
}
|
| 45 |
+
except Exception as e:
|
| 46 |
+
return JSONResponse(status_code=500, content={"error": str(e)})
|
| 47 |
+
|
| 48 |
+
if __name__ == "__main__":
|
| 49 |
+
port = int(os.environ.get("PORT", 3000))
|
| 50 |
+
print(f"✅ FastAPI server running on port {port}")
|
| 51 |
+
import uvicorn
|
| 52 |
+
uvicorn.run("main:app", host="0.0.0.0", port=port, log_level="info")
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn[standard]
|
| 3 |
+
psutil
|