Skip to content

Commit 6bcc174

Browse files
implementing redis for smoother user experience
1 parent 7adc537 commit 6bcc174

File tree

2 files changed

+45
-6
lines changed

2 files changed

+45
-6
lines changed

app.py

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# API imports
2-
from fastapi import FastAPI, Request
2+
from fastapi import FastAPI, Request, Depends
33
import groq
44
import os
55
from dotenv import load_dotenv
@@ -10,7 +10,11 @@
1010
from fastapi.responses import HTMLResponse
1111
from fastapi.templating import Jinja2Templates
1212
from pyfiglet import Figlet, FigletFont
13-
13+
from fastapi_cache import FastAPICache
14+
from fastapi_cache.backends.redis import RedisBackend
15+
from contextlib import asynccontextmanager
16+
import json
17+
from redis import asyncio as aioredis
1418
# Custom imports
1519
from topStocks import get_top_stocks
1620
from agents import multi_ai
@@ -24,7 +28,30 @@
2428

2529
if not GROQ_API_KEY:
2630
raise ValueError("Please provide a GROQ API key")
27-
31+
REDIS_URL = os.getenv("REDIS_URL")
32+
33+
@asynccontextmanager
34+
async def lifespan(_: FastAPI):
35+
redis_client = None
36+
37+
try:
38+
redis_client = aioredis.from_url(REDIS_URL, encoding="utf-8", decode_responses=True)
39+
FastAPICache.init(RedisBackend(redis_client), prefix="fastapi-cache")
40+
print("✅ Redis cache initialized successfully!")
41+
yield
42+
except Exception as e:
43+
print(f"❌ Redis Connection Error: {e}")
44+
yield
45+
finally:
46+
try:
47+
await FastAPICache.clear()
48+
if redis_client:
49+
await redis_client.close()
50+
print("🔴 Redis connection closed!")
51+
except Exception as e:
52+
print(f"❌ Error while closing Redis: {e}")
53+
54+
2855
app = FastAPI()
2956
app.add_middleware(
3057
CORSMiddleware,
@@ -35,16 +62,26 @@
3562
)
3663

3764
@app.get("/")
65+
@app.head("/")
3866
async def read_root(request: Request):
3967
text = "Investo-glow Backend API Server"
4068
return templates.TemplateResponse("base.html",{"request":request, "text": text})
4169

70+
def get_cache():
71+
return FastAPICache.get_backend()
4272

4373
@app.get("/top-stocks")
44-
async def read_top_stocks():
74+
async def read_top_stocks(cache: RedisBackend = Depends(get_cache)):
75+
cache_key = "top_stocks"
76+
cached_result = await cache.get(cache_key)
77+
if cached_result:
78+
return json.loads(cached_result)
79+
4580
top_stocks = ['AAPL', 'MSFT', 'AMZN', 'GOOGL']
4681
stock = " ".join(top_stocks)
4782
stock_info = get_top_stocks(stock)
83+
84+
await cache.set(cache_key, json.dumps(stock_info), 5)
4885
return stock_info
4986

5087
@app.get("/")

topStocks.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,10 @@ def get_top_stocks(symbols):
2121
'previousClose': info.get('previousClose', 'N/A'),
2222
'sector': info.get('sector', 'N/A')
2323
}
24-
stock_data.push(stock_info)
24+
25+
stock_data.append(stock_info)
26+
print("✅ Data fetching done successfully!")
2527
except Exception as e:
26-
print(f"Error fetching {symbols}: {e}")
28+
print(f"Error fetching {symbols}: {e}")
2729
time.sleep(5)
2830
return stock_data

0 commit comments

Comments
 (0)