Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,8 +1,9 @@
|
|
| 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 |
|
|
@@ -10,8 +11,11 @@ process = psutil.Process(os.getpid())
|
|
| 10 |
last_cpu_times = process.cpu_times()
|
| 11 |
last_time = time.time()
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
| 14 |
|
|
|
|
| 15 |
global last_cpu_times, last_time
|
| 16 |
now = time.time()
|
| 17 |
times = process.cpu_times()
|
|
@@ -19,19 +23,27 @@ def get_cpu_percent():
|
|
| 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 |
total = 0
|
| 28 |
for i in range(500000):
|
| 29 |
total += i
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
@app.get("/")
|
| 32 |
async def root():
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
@app.get("/metrics")
|
| 37 |
async def metrics():
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
from fastapi.responses import JSONResponse
|
| 3 |
import time
|
| 4 |
import psutil
|
| 5 |
import os
|
| 6 |
+
import asyncio
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
|
|
|
| 11 |
last_cpu_times = process.cpu_times()
|
| 12 |
last_time = time.time()
|
| 13 |
|
| 14 |
+
# Limit concurrent requests
|
| 15 |
+
MAX_CONCURRENT_REQUESTS = 20
|
| 16 |
+
semaphore = asyncio.Semaphore(MAX_CONCURRENT_REQUESTS)
|
| 17 |
|
| 18 |
+
def get_cpu_percent():
|
| 19 |
global last_cpu_times, last_time
|
| 20 |
now = time.time()
|
| 21 |
times = process.cpu_times()
|
|
|
|
| 23 |
cpu_used = (times.user - last_cpu_times.user) + (times.system - last_cpu_times.system)
|
| 24 |
last_cpu_times = times
|
| 25 |
last_time = now
|
|
|
|
| 26 |
return round((cpu_used / elapsed) * 100, 1)
|
| 27 |
|
| 28 |
def simulate_work():
|
|
|
|
| 29 |
total = 0
|
| 30 |
for i in range(500000):
|
| 31 |
total += i
|
| 32 |
+
return total
|
| 33 |
+
|
| 34 |
+
async def limited_worker():
|
| 35 |
+
async with semaphore:
|
| 36 |
+
# Actual work happens here
|
| 37 |
+
simulate_work()
|
| 38 |
+
return {"ok": True, "time": int(time.time() * 1000)}
|
| 39 |
|
| 40 |
@app.get("/")
|
| 41 |
async def root():
|
| 42 |
+
try:
|
| 43 |
+
result = await limited_worker()
|
| 44 |
+
return result
|
| 45 |
+
except Exception as e:
|
| 46 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 47 |
|
| 48 |
@app.get("/metrics")
|
| 49 |
async def metrics():
|