-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
87 lines (75 loc) · 2.93 KB
/
main.py
File metadata and controls
87 lines (75 loc) · 2.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import feedparser
import httpx
import asyncio
import uvicorn
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000", "http://127.0.0.1:3000"],
allow_methods=["*"],
allow_headers=["*"],
)
FEEDS = {
"XDA": "https://www.xda-developers.com/feed/",
"Polygon": "https://www.polygon.com/feed/"
}
# Spoof a real browser to avoid bot blocking
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
"Accept-Encoding": "gzip, deflate",
"Connection": "keep-alive",
}
async def fetch_feed(url: str) -> str:
"""Fetch RSS feed content with retry logic."""
async with httpx.AsyncClient(headers=HEADERS, timeout=10.0) as client:
for attempt in range(3):
try:
response = await client.get(url)
response.raise_for_status()
return response.text
except (httpx.RequestError, httpx.HTTPStatusError) as e:
if attempt == 2:
raise HTTPException(status_code=502, detail=f"Failed to fetch {url} after 3 attempts: {str(e)}")
await asyncio.sleep(1)
@app.get("/api/news")
async def get_news():
all_news = []
for source, url in FEEDS.items():
try:
# Fetch raw XML with resilient HTTP
xml_content = await fetch_feed(url)
# Parse locally (no network call in feedparser)
feed = feedparser.parse(xml_content)
for entry in feed.entries[:10]:
is_tech = any(x in entry.title.lower() for x in ['windows', 'dev', 'chip', 'gpu', 'ai', 'api'])
all_news.append({
"source": source,
"title": entry.title,
"link": entry.link,
"summary": entry.get('summary', '').replace('\n', ' ')[:200] + "...",
"is_tech": is_tech,
"published": entry.get('published', '')
})
except Exception as e:
# Log error but don't crash — skip bad feed
print(f"[ERROR] Skipping {source} feed: {e}")
continue
if not all_news:
raise HTTPException(status_code=503, detail="No feeds could be retrieved. Check network or feed URLs.")
return all_news
@app.get("/api/health")
async def health_check():
return {
"status": "ok",
"backend": "running",
"feeds": list(FEEDS.keys()),
"timestamp": "2025-12-20T12:00:00Z" # placeholder
}
if __name__ == "__main__":
import os
port = int(os.environ.get("PORT", 8000))
uvicorn.run(app, host="0.0.0.0", port=port, log_level="info")