49 أسطر
1.1 KiB
Python
49 أسطر
1.1 KiB
Python
from fastapi import FastAPI, Request
|
|
import time
|
|
|
|
app = FastAPI()
|
|
|
|
request_count = 0
|
|
last_response_time_ms = 0.0
|
|
|
|
|
|
@app.middleware("http")
|
|
async def track_requests(request: Request, call_next):
|
|
"""
|
|
Measures the REAL processing time of every request using a middleware
|
|
that wraps the actual handler, instead of measuring time inside the
|
|
handler itself (which always returns ~0ms).
|
|
We skip counting calls to /stats itself so the dashboard polling
|
|
doesn't inflate the request counter.
|
|
"""
|
|
global request_count, last_response_time_ms
|
|
|
|
start = time.time()
|
|
response = await call_next(request)
|
|
duration_ms = round((time.time() - start) * 1000, 2)
|
|
|
|
if request.url.path != "/stats":
|
|
request_count += 1
|
|
last_response_time_ms = duration_ms
|
|
|
|
return response
|
|
|
|
|
|
@app.get("/")
|
|
def home():
|
|
return {"message": "Application is running"}
|
|
|
|
|
|
@app.get("/health")
|
|
def health():
|
|
return {"status": "UP"}
|
|
|
|
|
|
@app.get("/stats")
|
|
def stats():
|
|
return {
|
|
"status": "UP",
|
|
"requests": request_count,
|
|
"response_time": last_response_time_ms
|
|
}
|