From 4c7e86138fbe0e7f14f2ef311d4034c4f437d3c1 Mon Sep 17 00:00:00 2001 From: Felix Pankratz Date: Tue, 29 Aug 2023 18:43:36 +0200 Subject: [PATCH] refactor --- hn.py | 41 +++++++++++++++++++++++++---------------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/hn.py b/hn.py index c75eb6c..09ebfd2 100755 --- a/hn.py +++ b/hn.py @@ -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