Here are the final versions of the files for your FastAPI-based web application:
1. models.py
from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime
from sqlalchemy.orm import declarative_base, sessionmaker
from datetime import datetime
Base = declarative_base()
class Story(Base):
__tablename__ = 'stories'
id = Column(Integer, primary_key=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) # Possible values: 'new', 'same', 'up', 'down', 'removed'
# Initialize database
engine = create_engine('sqlite:///hn-clone.db', connect_args={'check_same_thread': False})
Base.metadata.create_all(engine)
SessionLocal = sessionmaker(bind=engine)
2. hn-scraper.py
import asyncio
import aiohttp
import os
from datetime import datetime
from PIL import Image
from io import BytesIO
from models import Story, SessionLocal
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from bs4 import BeautifulSoup
engine = create_engine('sqlite:///hn-clone.db', connect_args={'check_same_thread': False})
SessionLocal = sessionmaker(bind=engine)
session = SessionLocal()
IMAGE_FOLDER = 'static/images'
os.makedirs(IMAGE_FOLDER, exist_ok=True)
async def fetch_story_ids():
async with aiohttp.ClientSession() as session:
async with session.get('https://hacker-news.firebaseio.com/v0/topstories.json') as resp:
top_stories = await resp.json()
return top_stories[:30]
async def fetch_story_details(session, story_id):
url = f'https://hacker-news.firebaseio.com/v0/item/{story_id}.json'
async with session.get(url) as resp:
return await resp.json()
async def fetch_open_graph(url):
og_data = {'image_url': '', 'description': ''}
try:
async with aiohttp.ClientSession() as session:
async with session.get(url, timeout=10) as resp:
html = await resp.text()
soup = BeautifulSoup(html, 'html.parser')
og_image = soup.find('meta', property='og:image')
og_description = soup.find('meta', property='og:description')
og_data['image_url'] = og_image['content'] if og_image else ''
og_data['description'] = og_description['content'] if og_description else ''
except Exception as e:
print(f'Error fetching Open Graph data from {url}: {e}')
return og_data
async def save_image(image_url, story_id):
try:
async with aiohttp.ClientSession() as session:
async with session.get(image_url, timeout=10) as resp:
img_data = await resp.read()
image = Image.open(BytesIO(img_data))
image.thumbnail((640, 640))
image_path = os.path.join(IMAGE_FOLDER, f'{story_id}.jpg')
image.save(image_path, format='JPEG')
return f'static/images/{story_id}.jpg'
except Exception as e:
print(f'Error saving image for story {story_id}: {e}')
return ''
async def scrape_stories():
story_ids = await fetch_story_ids()
tasks = []
async with aiohttp.ClientSession() as http_session:
for story_id in story_ids:
tasks.append(fetch_story_details(http_session, story_id))
stories = await asyncio.gather(*tasks)
for idx, story in enumerate(stories, 1):
if story:
hn_url = f'https://news.ycombinator.com/item?id={story["id"]}'
og_data = await fetch_open_graph(story.get('url', ''))
description = og_data.get('description', '')
image_url = og_data.get('image_url', '')
if not image_url:
# Fallback to favicon
parsed_url = aiohttp.helpers.urlparse(story.get('url', ''))
image_url = f'{parsed_url.scheme}://{parsed_url.netloc}/favicon.ico'
image_path = await save_image(image_url, story['id']) if image_url else ''
# Check if story exists
db_story = session.query(Story).filter_by(id=story['id']).first()
if not db_story:
trend = 'new'
last_position = None
else:
last_position = db_story.current_position
if last_position == idx:
trend = 'same'
elif last_position > idx:
trend = 'up'
elif last_position < idx:
trend = 'down'
else:
trend = 'same'
# Update or insert story
db_story = Story(
id=story['id'],
title=story.get('title', ''),
url=story.get('url', ''),
hn_url=hn_url,
score=story.get('score', 0),
poster=story.get('by', ''),
comments_count=story.get('descendants', 0),
time_posted=datetime.fromtimestamp(story.get('time', 0)),
description=description,
image_url=image_path,
last_position=last_position,
current_position=idx,
trend=trend
)
session.merge(db_story)
# Handle removed stories
existing_story_ids = [s.id for s in session.query(Story).all()]
removed_stories = set(existing_story_ids) - set([s['id'] for s in stories if s])
for story_id in removed_stories:
db_story = session.query(Story).filter_by(id=story_id).first()
db_story.last_position = db_story.current_position
db_story.current_position = None
db_story.trend = 'removed'
session.merge(db_story)
session.commit()
if __name__ == '__main__':
asyncio.run(scrape_stories())
3. main.py
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from models import SessionLocal, Story
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from datetime import datetime
import asyncio
import threading
import hn_scraper # Import the scraper module
app = FastAPI()
templates = Jinja2Templates(directory='templates')
app.mount("/static", StaticFiles(directory="static"), name="static")
engine = create_engine('sqlite:///hn-clone.db', connect_args={'check_same_thread': False})
SessionLocal = sessionmaker(bind=engine)
def start_background_scraper():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
async def scrape_periodically():
while True:
print(f'{datetime.now()}: Starting scrape...')
await hn_scraper.scrape_stories()
print(f'{datetime.now()}: Scrape completed. Waiting for 3 minutes...')
await asyncio.sleep(180) # Wait for 3 minutes
loop.run_until_complete(scrape_periodically())
# Start the background scraper in a separate thread
threading.Thread(target=start_background_scraper, daemon=True).start()
@app.get("/")
def index(request: Request):
session = SessionLocal()
stories = session.query(Story).filter(Story.current_position != None).order_by(Story.current_position).all()
last_updated = datetime.now()
return templates.TemplateResponse('index.html', {
'request': request,
'stories': stories,
'last_updated': last_updated
})
4. templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hacker News Clone</title>
<link rel="stylesheet" href="/static/style.css">
<script>
// Auto-refresh every 3 minutes
setTimeout(() => {
window.location.reload();
}, 180000);
</script>
</head>
<body>
<h1>Hacker News Top 30 Stories</h1>
<p>Last Updated: {{ last_updated.strftime('%Y-%m-%d %H:%M:%S') }}</p>
<button onclick="window.location.reload();">Manual Refresh</button>
<table>
<thead>
<tr>
<th>Trend</th>
<th>Position</th>
<th>Title</th>
<th>Image</th>
<th>Score</th>
<th>Comments</th>
<th>Poster</th>
<th>Time Posted</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{% for story in stories %}
<tr>
<td>
{% if story.trend == 'up' %}
<img src="/static/up.png" alt="Up" width="16" height="16">
{% elif story.trend == 'down' %}
<img src="/static/down.png" alt="Down" width="16" height="16">
{% elif story.trend == 'same' %}
<img src="/static/same.png" alt="Same" width="16" height="16">
{% elif story.trend == 'new' %}
<img src="/static/new.png" alt="New" width="16" height="16">
{% elif story.trend == 'removed' %}
<img src="/static/removed.png" alt="Removed" width="16" height="16">
{% endif %}
</td>
<td>{{ story.current_position }}</td>
<td><a href="{{ story.url }}">{{ story.title }}</a></td>
<td>
{% if story.image_url %}
<img src="/{{ story.image_url }}" alt="Story Image" width="100">
{% else %}
<img src="/static/placeholder.jpg" alt="Placeholder" width="100">
{% endif %}
</td>
<td>{{ story.score }}</td>
<td><a href="{{ story.hn_url }}">{{ story.comments_count }}</a></td>
<td>{{ story.poster }}</td>
<td>{{ story.time_posted.strftime('%Y-%m-%d %H:%M:%S') }}</td>
<td>{{ story.description }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
5. static/style.css
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1 {
text-align: center;
}
button {
margin-bottom: 20px;
padding: 10px 20px;
font-size: 16px;
}
table {
width: 100%;
border-collapse: collapse;
}
table thead {
background-color: #f2f2f2;
}
table th, table td {
padding: 12px;
border: 1px solid #ddd;
text-align: left;
vertical-align: top;
}
table tr:nth-child(even) {
background-color: #fafafa;
}
img {
max-width: 100px;
height: auto;
}
@media (max-width: 768px) {
table, thead, tbody, th, td, tr {
display: block;
}
table tr {
margin-bottom: 15px;
}
table td {
text-align: right;
padding-left: 50%;
position: relative;
}
table td:before {
content: attr(data-label);
position: absolute;
left: 0;
width: 45%;
padding-left: 15px;
font-weight: bold;
text-align: left;
}
}
6. Ensure the following directory structure:
- main.py
- hn-scraper.py
- models.py
- hn-clone.db # This will be created automatically
- templates/
- index.html
- static/
- style.css
- images/ # Images will be saved here
- placeholder.jpg # Provide a placeholder image
- up.png # Trend icons
- down.png
- same.png
- new.png
- removed.png
Notes:
-
Trend Icons: You'll need to add images for the trend icons (up.png, down.png, same.png, new.png, removed.png) in the static directory.
-
Placeholder Image: Add a placeholder.jpg image in the static directory to display when no image is available.
-
Database: The SQLite database hn-clone.db will be created automatically when you run the application.
-
Running the Application:
-
Install the required packages:
pip install fastapi uvicorn sqlalchemy aiohttp pillow beautifulsoup4 jinja2
-
Run the FastAPI application:
uvicorn main:app --reload
-
Background Scraper: The scraper runs in a background thread within the FastAPI application, refreshing data every 3 minutes.
-
Auto-Refresh: The page auto-refreshes every 3 minutes to fetch the latest stories.
-
Manual Refresh: Users can click the "Manual Refresh" button to reload the page at any time.
-
Responsive Design: The CSS is designed to be responsive for different screen sizes.
Please make sure to adjust file paths and any additional configurations as needed for your environment. Let me know if you have any questions or need further assistance!