From c6d8b82a90ea3e2c105d070ab83822e92060593e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=A1clav=20=C5=A0milauer?= Date: Sat, 19 Oct 2024 17:47:24 +0200 Subject: [PATCH] Add caching decorator to safeapi (TTL 2s) --- mupifDB/api/safeapi.py | 21 ++++++++++++++++++++- requirements.txt | 1 + 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/mupifDB/api/safeapi.py b/mupifDB/api/safeapi.py index ae0db28..9a7a8d9 100644 --- a/mupifDB/api/safeapi.py +++ b/mupifDB/api/safeapi.py @@ -4,13 +4,28 @@ import mupif as mp import os -app = fastapi.FastAPI(openapi_tags=[{'name':'Stats'}]) +### BEGIN CACHING (should be ported to master later) +from fastapi_cache import FastAPICache +from fastapi_cache.decorator import cache +from fastapi_cache.backends.inmemory import InMemoryBackend +from contextlib import asynccontextmanager +from collections.abc import AsyncIterator +@asynccontextmanager +async def lifespan(_: fastapi.FastAPI) -> AsyncIterator[None]: + FastAPICache.init(InMemoryBackend()) + yield + +app = fastapi.FastAPI(openapi_tags=[{'name':'Stats'}],lifespan=lifespan) +### END CACHING + + mongoClient = pymongo.MongoClient("mongodb://localhost:27017") @app.get("/status2/", tags=["Stats"]) +@cache(expire=2) def get_status2(): ns = None try: @@ -38,20 +53,24 @@ def get_status2(): @app.get("/scheduler-status2/", tags=["Stats"]) +@cache(expire=2) def get_scheduler_status2(): ns = mp.pyroutil.connectNameserver(); return mp.monitor.schedulerInfo(ns) @app.get("/ns-status2/", tags=["Stats"]) +@cache(expire=2) def get_ns_status2(): ns = mp.pyroutil.connectNameserver(); return mp.monitor.nsInfo(ns) @app.get("/vpn-status2/", tags=["Stats"]) +@cache(expire=2) def get_vpn_status2(): return mp.monitor.vpnInfo(hidePriv=False) @app.get("/jobmans-status2/", tags=["Stats"]) +@cache(expire=2) def get_jobmans_status2(): ns = mp.pyroutil.connectNameserver(); return mp.monitor.jobmanInfo(ns) diff --git a/requirements.txt b/requirements.txt index b5abb1c..9406212 100644 --- a/requirements.txt +++ b/requirements.txt @@ -15,6 +15,7 @@ Werkzeug==2.2.2 psutil fastapi uvicorn[standard] +fastapi-cache2 python-multipart networkx astropy