master
Felix Pankratz 1 year ago
parent d43389b20a
commit 4c7e86138f

41
hn.py

@ -22,6 +22,26 @@ class Story:
votes: int votes: int
comments: 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): def footer(stdscr, content):
stdscr.addstr(curses.LINES-1, 0, content, curses.A_REVERSE) stdscr.addstr(curses.LINES-1, 0, content, curses.A_REVERSE)
@ -29,27 +49,16 @@ def footer(stdscr, content):
def main(stdscr): def main(stdscr):
stdscr.clear() stdscr.clear()
height, width = stdscr.getmaxyx() _, width = stdscr.getmaxyx();
num_stories = curses.LINES - 3 # headline, detail, footer num_stories = curses.LINES - 3 # headline, detail, footer
# Query Hacker News API for top stories and their titles/links topstories = get_topstories()
# 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()
stories = [] stories = []
for idx, i in enumerate(ids[:num_stories]): for idx, i in enumerate(topstories[:num_stories]):
stdscr.clear() stdscr.clear()
footer(stdscr, f'[{spinner_states[idx%4]}] Getting stories...') footer(stdscr, f'[{spinner_states[idx%4]}] Getting stories...')
stdscr.refresh() stdscr.refresh()
story_url = f'https://hacker-news.firebaseio.com/v0/item/{i}.json' stories.append(get_story(i))
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))
# Display list of stories in terminal window with arrow key navigation # Display list of stories in terminal window with arrow key navigation
current_pos = 0 current_pos = 0

Loading…
Cancel
Save