Here are the final versions of the files for the FastAPI-based web application that meets your requirements:
main.py
# main.py
import asyncio
from datetime import datetime, timedelta
from io import BytesIO
import os
import time
import aiohttp
from aiohttp import ClientError
from bs4 import BeautifulSoup
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from PIL import Image
from sqlalchemy import (
Column,
DateTime,
Integer,
String,
Text,
create_engine,
func,
or_,
)
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session, sessionmaker
app = FastAPI()
# Database setup
DATABASE_URL = "sqlite:///./hackernews.db"
engine = create_engine(
DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(bind=engine)
Base = declarative_base()
# Define the Story model
class Story(Base):
__tablename__ = "stories"
id = Column(Integer, primary_key=True, index=True)
title = Column(String)
url = Column(String)
hn_url = Column(String)
score = Column(Integer)
poster = Column(String)
comments_count = Column(Integer)
time_posted = Column(DateTime)
description = Column(Text)
image_url = Column(String)
last_position = Column(Integer)
current_position = Column(Integer)
trend = Column(String)
Base.metadata.create_all(bind=engine)
# Static files and templates setup
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
# Global variable to store the last update time
last_update = datetime.utcnow() - timedelta(minutes=5)
# Middleware to add last update time to headers
@app.middleware("http")
async def add_update_time_header(request: Request, call_next):
response = await call_next(request)
response.headers["X-Last-Update"] = last_update.strftime(
"%Y-%m-%d %H:%M:%S UTC"
)
return response
# Function to fetch top stories
async def fetch_top_stories():
global last_update
last_update = datetime.utcnow()
async with aiohttp.ClientSession() as session:
try:
async with session.get("https://news.ycombinator.com/") as response:
text = await response.text()
soup = BeautifulSoup(text, "html.parser")
rows = soup.find_all("tr", class_="athing")
stories = []
for idx, row in enumerate(rows[:30]):
story_id = int(row["id"])
title_tag = row.find("a", class_="storylink")
title = title_tag.text if title_tag else "No Title"
url = title_tag["href"] if title_tag else "#"
if url.startswith("item?id="):
url = f"https://news.ycombinator.com/{url}"
hn_url = f"https://news.ycombinator.com/item?id={story_id}"
subtext_row = row.find_next_sibling("tr")
score_tag = subtext_row.find("span", class_="score")
score = int(score_tag.text.split()[0]) if score_tag else 0
poster_tag = subtext_row.find("a", class_="hnuser")
poster = poster_tag.text if poster_tag else "N/A"
comments_tag = subtext_row.find_all("a")[-1]
comments_text = comments_tag.text
if "comment" in comments_text:
comments_count = int(
comments_text.split()[0]
if comments_text.split()[0].isdigit()
else 0
)
else:
comments_count = 0
age_tag = subtext_row.find("span", class_="age")
time_posted = datetime.utcnow()
if age_tag and age_tag.get("title"):
time_str = age_tag["title"]
time_posted = datetime.strptime(
time_str, "%Y-%m-%d %H:%M:%S"
)
# Fetch metadata
description, image_url = await fetch_metadata(session, url)
stories.append(
{
"id": story_id,
"title": title,
"url": url,
"hn_url": hn_url,
"score": score,
"poster": poster,
"comments_count": comments_count,
"time_posted": time_posted,
"description": description,
"image_url": image_url,
"current_position": idx + 1,
}
)
# Update the database with new stories
update_database(stories)
except ClientError as e:
print(f"HTTP error while fetching stories: {e}")
# Function to fetch metadata
async def fetch_metadata(session, url):
description = ""
image_url = ""
# Check if URL is valid
if not url.startswith("http"):
return description, "/static/images/placeholder.jpg"
# Check for cached images
image_filename = os.path.join(
"static", "images", f"{hash(url)}.jpg"
)
if os.path.exists(image_filename):
return description, f"/{image_filename}"
try:
async with session.get(url, timeout=10) as response:
html = await response.text()
soup = BeautifulSoup(html, "html.parser")
# Get description
og_desc = soup.find("meta", property="og:description")
if og_desc and og_desc.get("content"):
description = og_desc["content"].strip()
# Get image
og_image = soup.find("meta", property="og:image")
if og_image and og_image.get("content"):
image_url = og_image["content"]
else:
# Fallback to favicon
favicon = soup.find("link", rel="icon")
if favicon and favicon.get("href"):
image_url = favicon["href"]
# Save and resize image
if image_url:
image_path = await save_image(image_url, image_filename)
image_url = f"/{image_path}"
else:
image_url = "/static/images/placeholder.jpg"
except Exception as e:
print(f"Error fetching metadata for {url}: {e}")
image_url = "/static/images/placeholder.jpg"
return description, image_url
# Function to save and resize images
async def save_image(image_url, save_path):
try:
response = requests.get(image_url, timeout=10)
image = Image.open(BytesIO(response.content))
image.thumbnail((640, 640))
image_format = "JPEG"
if image.mode in ("RGBA", "P"):
image = image.convert("RGB")
os.makedirs(os.path.dirname(save_path), exist_ok=True)
image.save(save_path, image_format)
return save_path
except Exception as e:
print(f"Error saving image {image_url}: {e}")
return "static/images/placeholder.jpg"
# Function to update the database
def update_database(stories):
db = SessionLocal()
try:
existing_stories = db.query(Story).all()
existing_ids = [story.id for story in existing_stories]
# Update existing stories and insert new ones
for story_data in stories:
db_story = (
db.query(Story)
.filter(Story.id == story_data["id"])
.first()
)
if db_story:
db_story.last_position = db_story.current_position
db_story.current_position = story_data["current_position"]
db_story.title = story_data["title"]
db_story.url = story_data["url"]
db_story.hn_url = story_data["hn_url"]
db_story.score = story_data["score"]
db_story.poster = story_data["poster"]
db_story.comments_count = story_data["comments_count"]
db_story.time_posted = story_data["time_posted"]
db_story.description = story_data["description"]
db_story.image_url = story_data["image_url"]
# Determine trend
if db_story.last_position is None:
db_story.trend = "new"
elif db_story.current_position < db_story.last_position:
db_story.trend = "up"
elif db_story.current_position > db_story.last_position:
db_story.trend = "down"
else:
db_story.trend = "same"
else:
# New story
new_story = Story(
id=story_data["id"],
title=story_data["title"],
url=story_data["url"],
hn_url=story_data["hn_url"],
score=story_data["score"],
poster=story_data["poster"],
comments_count=story_data["comments_count"],
time_posted=story_data["time_posted"],
description=story_data["description"],
image_url=story_data["image_url"],
last_position=None,
current_position=story_data["current_position"],
trend="new",
)
db.add(new_story)
# Mark stories not in top 30 as removed
current_ids = [s["id"] for s in stories]
removed_stories = (
db.query(Story)
.filter(
or_(
~Story.id.in_(current_ids),
Story.current_position == None,
)
)
.all()
)
for removed_story in removed_stories:
removed_story.last_position = removed_story.current_position
removed_story.current_position = None
removed_story.trend = "removed"
db.commit()
except SQLAlchemyError as e:
print(f"Database error: {e}")
db.rollback()
finally:
db.close()
# Schedule the fetch_top_stories function
@app.on_event("startup")
async def startup_event():
asyncio.create_task(schedule_fetch())
async def schedule_fetch():
while True:
await fetch_top_stories()
await asyncio.sleep(180) # Refresh every 3 minutes
# Route for the homepage
@app.get("/")
def index(request: Request):
db = SessionLocal()
try:
stories = (
db.query(Story)
.filter(Story.current_position != None)
.order_by(Story.current_position)
.all()
)
finally:
db.close()
return templates.TemplateResponse(
"index.html", {"request": request, "stories": stories}
)
# Manual refresh route
@app.get("/refresh")
async def refresh():
await fetch_top_stories()
return RedirectResponse(url="/")
templates/index.html
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hacker News Top Stories</title>
<link rel="stylesheet" href="/static/css/style.css">
<meta http-equiv="refresh" content="180">
</head>
<body>
<div class="container">
<h1>Hacker News Top Stories</h1>
<p>Last updated: {{ request.headers['X-Last-Update'] }}</p>
<button onclick="window.location.reload();">Refresh</button>
<div class="stories">
{% for story in stories %}
<div class="story">
<div class="trend">
{% if story.trend == 'up' %}
<span class="arrow up">↑</span>
{% elif story.trend == 'down' %}
<span class="arrow down">↓</span>
{% elif story.trend == 'new' %}
<span class="arrow new">●</span>
{% elif story.trend == 'same' %}
<span class="arrow same">→</span>
{% elif story.trend == 'removed' %}
<span class="arrow removed">×</span>
{% endif %}
<span class="position">{{ story.current_position }}</span>
</div>
<div class="content">
<h2><a href="{{ story.url }}" target="_blank">{{ story.title }}</a></h2>
<p>{{ story.description }}</p>
<p class="meta">
<span>Score: {{ story.score }}</span> |
<span>Comments: {{ story.comments_count }}</span> |
<span>Posted by {{ story.poster }}</span> |
<span>Time: {{ story.time_posted.strftime('%Y-%m-%d %H:%M:%S') }} UTC</span> |
<a href="{{ story.hn_url }}" target="_blank">HN Link</a>
</p>
</div>
<div class="image">
<img src="{{ story.image_url }}" alt="Image">
</div>
</div>
{% endfor %}
</div>
</div>
</body>
</html>
static/css/style.css
/* static/css/style.css */
body {
font-family: Arial, sans-serif;
background-color: #f6f6ef;
margin: 0;
padding: 0;
}
.container {
width: 95%;
margin: 20px auto;
}
h1 {
text-align: center;
color: #ff6600;
}
.button {
display: block;
margin: 10px auto;
}
.stories {
display: flex;
flex-direction: column;
}
.story {
display: flex;
flex-wrap: wrap;
border-bottom: 1px solid #ccc;
padding: 15px 0;
}
.trend {
width: 60px;
text-align: center;
font-size: 24px;
}
.arrow.up {
color: green;
}
.arrow.down {
color: red;
}
.arrow.same {
color: gray;
}
.arrow.new {
color: blue;
}
.arrow.removed {
color: black;
}
.content {
flex: 1;
padding: 0 15px;
}
.content h2 {
margin: 0 0 10px 0;
}
.content p {
margin: 0 0 10px 0;
}
.content .meta {
font-size: 0.9em;
color: #555;
}
.image {
width: 120px;
text-align: center;
}
.image img {
max-width: 100px;
max-height: 100px;
object-fit: cover;
}
@media (max-width: 768px) {
.trend {
width: 100%;
text-align: left;
font-size: 18px;
}
.content {
padding: 10px 0;
}
.image {
width: 100%;
text-align: center;
margin-top: 10px;
}
}
Note: Make sure to create the necessary directories:
templates/ for the index.html file.
static/css/ for the style.css file.
static/images/ for storing images and include a placeholder.jpg image for cases where no image is available.
Instructions to Run the Application:
-
Install the required packages:
pip install fastapi sqlalchemy aiohttp beautifulsoup4 uvicorn pillow requests
-
Run the application using Uvicorn:
uvicorn main:app --reload
-
Open your browser and navigate to http://localhost:8000 to view the application.
Additional Notes:
- The application fetches and displays the top 30 stories from Hacker News and updates every 3 minutes.
- It uses an SQLite database to store and track the stories' data and their positions.
- The metadata extraction uses Open Graph tags to fetch the description and images, with caching implemented via saved images.
- Images are resized to a maximum width of 640 pixels and stored as JPG.
- The user interface is responsive and includes manual refresh functionality.
Feel free to customize and enhance the application as needed.