raghavNCI commited on
Commit
2ec0990
·
1 Parent(s): 2aed3fd

fetch news from redis

Browse files
Files changed (1) hide show
  1. routes.py +12 -36
routes.py CHANGED
@@ -1,54 +1,30 @@
1
  import os
2
- import requests
3
- from fastapi import APIRouter, Query
4
  from dotenv import load_dotenv
 
5
 
6
  load_dotenv()
7
 
8
-
9
  router = APIRouter()
10
 
11
- GNEWS_API_KEY = os.getenv("GNEWS_API_KEY")
12
-
13
  @router.get("/news/category/{category}")
14
- def get_news_by_category(category: str, limit: int = 5):
15
- base_url = "https://gnews.io/api/v4/top-headlines"
16
- params = {
17
- "topic": category,
18
- "lang": "en",
19
- "max": limit,
20
- "expand": "content",
21
- "token": GNEWS_API_KEY
22
- }
23
-
24
  try:
25
- response = requests.get(base_url, params=params, timeout=10)
26
- response.raise_for_status() # raise exception for non-200 responses
27
- data = response.json()
28
-
29
  articles = []
30
- for article in data.get("articles", []):
31
- articles.append({
32
- "title": article["title"],
33
- "url": article["url"],
34
- "description": article.get("description"),
35
- "content": article.get("content"),
36
- "publishedAt": article["publishedAt"],
37
- "image": article.get("image"),
38
- "source": article["source"]["name"]
39
- })
40
 
41
- return articles
 
 
 
42
 
43
- except requests.exceptions.RequestException as e:
44
- print(f"[ERROR] Failed to fetch news: {e}")
45
- return {"error": "Failed to fetch news from GNews API."}
46
 
47
  except Exception as e:
48
- print(f"[ERROR] Unexpected error: {e}")
49
- return {"error": "An unexpected error occurred."}
50
 
51
 
52
  @router.get("/")
53
  async def root():
54
- return {"message": "LucidFeed backend is up and running!"}
 
1
  import os
2
+ from fastapi import APIRouter
 
3
  from dotenv import load_dotenv
4
+ from redis_client import redis_client as r
5
 
6
  load_dotenv()
7
 
 
8
  router = APIRouter()
9
 
 
 
10
  @router.get("/news/category/{category}")
11
+ def get_cached_articles_by_category(category: str, limit: int = 5):
 
 
 
 
 
 
 
 
 
12
  try:
13
+ article_ids = list(r.smembers(f"category:{category}"))[:limit]
 
 
 
14
  articles = []
 
 
 
 
 
 
 
 
 
 
15
 
16
+ for article_id in article_ids:
17
+ article_data = r.hgetall(f"article:{article_id}")
18
+ if article_data:
19
+ articles.append(article_data)
20
 
21
+ return articles
 
 
22
 
23
  except Exception as e:
24
+ print(f"[ERROR] Failed to fetch cached articles: {e}")
25
+ return {"error": "Failed to fetch articles from cache."}
26
 
27
 
28
  @router.get("/")
29
  async def root():
30
+ return {"message": "LucidFeed backend is up and running!"}