This commit is contained in:
Felix Pankratz 2023-08-29 18:43:36 +02:00
parent d43389b20a
commit 4c7e86138f

41
hn.py
View File

@ -22,6 +22,26 @@ class Story:
votes: int
comments: int
def get_topstories():
# Query Hacker News API for top stories and their titles/links
# returns the top 500 stories, so quite enough.
url = 'https://hacker-news.firebaseio.com/v0/topstories.json'
r = requests.get(url)
if not r.ok:
raise Exception('Error fetching data from Hacker News API')
return r.json()
def get_story(story_id):
story_url = f'https://hacker-news.firebaseio.com/v0/item/{story_id}.json'
s = requests.get(story_url).json()
return Story(s['id'],
s['title'],
s['url'] if 'url' in s else 'No URL',
s['by'],
s['score'],
len(s['kids']) if 'kids' in s else 0)
def footer(stdscr, content):
stdscr.addstr(curses.LINES-1, 0, content, curses.A_REVERSE)
@ -29,27 +49,16 @@ def footer(stdscr, content):
def main(stdscr):
stdscr.clear()
height, width = stdscr.getmaxyx()
_, width = stdscr.getmaxyx();
num_stories = curses.LINES - 3 # headline, detail, footer
# Query Hacker News API for top stories and their titles/links
# returns the top 500 stories, so quite enough.
url = 'https://hacker-news.firebaseio.com/v0/topstories.json'
r = requests.get(url)
if not r.ok:
raise Exception('Error fetching data from Hacker News API')
ids = r.json()
topstories = get_topstories()
stories = []
for idx, i in enumerate(ids[:num_stories]):
for idx, i in enumerate(topstories[:num_stories]):
stdscr.clear()
footer(stdscr, f'[{spinner_states[idx%4]}] Getting stories...')
stdscr.refresh()
story_url = f'https://hacker-news.firebaseio.com/v0/item/{i}.json'
s = requests.get(story_url).json()
stories.append(Story(s['id'],
s['title'],
s['url'] if 'url' in s else 'No URL',
s['by'], s['score'],
len(s['kids']) if 'kids' in s else 0))
stories.append(get_story(i))
# Display list of stories in terminal window with arrow key navigation
current_pos = 0