내 프로젝트 6 : Top 10 뉴스 앱 (with Flask + Hacker News API)
I’m happy to translate the article for you, but I need the actual text you’d like translated. Could you please paste the content (or the portions you want translated) here? I’ll keep the source link, formatting, markdown, and any code blocks exactly as they are while translating the rest into Korean.
📖 소개
독일어를 공부하면서 나는 종종 뉴스 기사를 읽기 연습으로 활용한다.
하지만 간단히 헤드라인만 빠르게 확인하고 싶을 때, 뉴스를 바로 접근하기가 쉽지 않다.
그래서 최신 주요 뉴스를 자동으로 가져와 깔끔하고 간단한 인터페이스에 표시하는 작은 프로젝트를 만들기로 했다.
이렇게 하면 뉴스를 쉽게 확인할 수 있을 뿐만 아니라, Flask와 외부 API를 활용해 유용한 무언가를 만들면서 동시에 학습할 수 있다.
🧱 1. Project Overview
Hacker News에서 Top 10 stories를 가져와 제목과 URL을 표시하는 최소한의 Flask 웹 앱입니다.
이 프로젝트가 보여주는 내용
- 외부 API 데이터 가져오기
- JSON 파싱
- Flask 라우팅 및 템플릿 렌더링
- 백엔드 데이터를 HTML에 전달
- Tailwind CSS를 이용한 UI 스타일링
작지만 API 통합을 배우기에 완벽합니다.
📂 2. 프로젝트 구조
news_app/
│
├── app.py # Main Flask app
├── tempCodeRunnerFile.py # Auto‑generated runner file (VS Code)
└── templates/
└── index.html # Front‑end template
📝 tempCodeRunnerFile.py란?
VS Code는 단일 파일이나 선택한 코드를 실행할 때 이 파일을 자동으로 생성합니다.
app.py와 동일한 로직을 포함하지만 일시적인 실행에만 사용됩니다.
블로그에 이 파일을 포함시킨 이유는 프로젝트 구조가 실제 로컬 폴더와 정확히 일치하도록 하기 위해서입니다.
🌐 3. API Used — Hacker News API
Hacker News는 Firebase에 호스팅된 무료 JSON API를 제공합니다.
Top stories ID list
https://hacker-news.firebaseio.com/v0/topstories.json
Retrieve a single story
https://hacker-news.firebaseio.com/v0/item/.json
우리는 단순히 top‑stories 목록을 가져와서 처음 10개의 항목을 선택합니다.
🖥️ 4. 백엔드 코드 — app.py
from flask import Flask, render_template
import requests
app = Flask(__name__)
TOP_STORIES_URL = "https://hacker-news.firebaseio.com/v0/topstories.json"
ITEM_URL = "https://hacker-news.firebaseio.com/v0/item/{}.json"
@app.route("/")
def index():
# 1) Fetch top story IDs
ids = requests.get(TOP_STORIES_URL).json()
# 2) Retrieve the top 10 stories
news_list = []
for item_id in ids[:10]:
item = requests.get(ITEM_URL.format(item_id)).json()
news_list.append({
"title": item.get("title"),
"url": item.get("url")
})
# 3) Render the HTML template
return render_template("index.html", news=news_list)
if __name__ == "__main__":
app.run(debug=True)
📄 5. tempCodeRunnerFile.py (자동 생성)
from flask import Flask, render_template
import requests
app = Flask(__name__)
TOP_STORIES_URL = "https://hacker-news.firebaseio.com/v0/topstories.json"
ITEM_URL = "https://hacker-news.firebaseio.com/v0/item/{}.json"
@app.route("/")
def index():
ids = requests.get(TOP_STORIES_URL).json()
news_list = []
for item_id in ids[:10]:
item = requests.get(ITEM_URL.format(item_id)).json()
news_list.append({
"title": item.get("title"),
"url": item.get("url")
})
return render_template("index.html", news=news_list)
if __name__ == "__main__":
app.run(debug=True)
🎨 6. 프런트‑엔드 템플릿 — templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Top News</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap');
body { font-family: 'Inter', sans-serif; }
</style>
</head>
<body>
<h2>Top News</h2>
<h3>Hacker News Top 10</h3>
{% for item in news %}
<div>
<span>{{ loop.index }}</span>
<strong>{{ item.title }}</strong>
{% if item.url %}
<a href="{{ item.url }}">{{ item.url }}</a>
{% else %}
<span>No link available</span>
{% endif %}
</div>
{% endfor %}
</body>
</html>
이것으로 끝입니다! app.py를 실행하고 브라우저에서 http://127.0.0.1:5000/를 열면, 깔끔한 Tailwind 스타일 UI로 최신 Hacker News 상위 10개 헤드라인을 확인할 수 있습니다. 즐거운 코딩 되세요!
7. 실행 방법
의존성 설치
pip install flask requests
앱 실행
python app.py
브라우저에서 열기
http://127.0.0.1:5000
📚 8. 내가 배운 것
- 공개 API를 활용하는 방법
- JSON을 올바르게 파싱하는 방법
- Flask 라우팅 + 렌더링 작동 방식
- API 데이터를 HTML 템플릿에 전달하는 방법
- TailwindCSS를 사용한 기본 UI 구축
가볍지만 매우 실용적인 프로젝트.
📌 9. 향후 개선 사항 (쉬운 작업)
- 상위 20, 30, 또는 50개의 스토리 표시
- 작성자 이름과 점수 표시
- “시간 전” 형식 추가
- 다크/라이트 모드 토글 추가
- 검색/필터 기능 추가
템플릿 스니펫 (참고용)
{{ item.url }}
{% endif %}
{% endfor %}
{% if not news %}
No news available.
{% else %}
Data provided by Hacker News API
{% endif %}