Skip to content

Commit 77eaf9f

Browse files
Merge pull request #8 from yashksaini-coder/kush2
Kush2
2 parents 7adc537 + 59e8c9c commit 77eaf9f

File tree

2 files changed

+46
-6
lines changed

2 files changed

+46
-6
lines changed

app.py

Lines changed: 42 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,31 @@
2428

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

3765
@app.get("/")
66+
@app.head("/")
3867
async def read_root(request: Request):
3968
text = "Investo-glow Backend API Server"
4069
return templates.TemplateResponse("base.html",{"request":request, "text": text})
4170

71+
def get_cache():
72+
return FastAPICache.get_backend()
4273

4374
@app.get("/top-stocks")
44-
async def read_top_stocks():
75+
async def read_top_stocks(cache: RedisBackend = Depends(get_cache)):
76+
cache_key = "top_stocks"
77+
cached_result = await cache.get(cache_key)
78+
if cached_result:
79+
return json.loads(cached_result)
80+
4581
top_stocks = ['AAPL', 'MSFT', 'AMZN', 'GOOGL']
4682
stock = " ".join(top_stocks)
4783
stock_info = get_top_stocks(stock)
84+
85+
await cache.set(cache_key, json.dumps(stock_info), 5)
4886
return stock_info
4987

5088
@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)