|
1 | 1 | # API imports |
2 | | -from fastapi import FastAPI, Request |
| 2 | +from fastapi import FastAPI, Request, Depends |
3 | 3 | import groq |
4 | 4 | import os |
5 | 5 | from dotenv import load_dotenv |
|
10 | 10 | from fastapi.responses import HTMLResponse |
11 | 11 | from fastapi.templating import Jinja2Templates |
12 | 12 | 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 |
14 | 18 | # Custom imports |
15 | 19 | from topStocks import get_top_stocks |
16 | 20 | from agents import multi_ai |
|
24 | 28 |
|
25 | 29 | if not GROQ_API_KEY: |
26 | 30 | 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 | + |
28 | 56 | app = FastAPI() |
29 | 57 | app.add_middleware( |
30 | 58 | CORSMiddleware, |
|
35 | 63 | ) |
36 | 64 |
|
37 | 65 | @app.get("/") |
| 66 | +@app.head("/") |
38 | 67 | async def read_root(request: Request): |
39 | 68 | text = "Investo-glow Backend API Server" |
40 | 69 | return templates.TemplateResponse("base.html",{"request":request, "text": text}) |
41 | 70 |
|
| 71 | +def get_cache(): |
| 72 | + return FastAPICache.get_backend() |
42 | 73 |
|
43 | 74 | @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 | + |
45 | 81 | top_stocks = ['AAPL', 'MSFT', 'AMZN', 'GOOGL'] |
46 | 82 | stock = " ".join(top_stocks) |
47 | 83 | stock_info = get_top_stocks(stock) |
| 84 | + |
| 85 | + await cache.set(cache_key, json.dumps(stock_info), 5) |
48 | 86 | return stock_info |
49 | 87 |
|
50 | 88 | @app.get("/") |
|
0 commit comments