refactor
parent
4c7e86138f
commit
726bec2a86
@ -0,0 +1,38 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
import requests
|
||||||
|
from dataclasses import dataclass
|
||||||
|
@dataclass
|
||||||
|
class Story:
|
||||||
|
id: int
|
||||||
|
title: str
|
||||||
|
link: str
|
||||||
|
author: str
|
||||||
|
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 main():
|
||||||
|
ts = get_topstories()
|
||||||
|
s = get_story(ts[0])
|
||||||
|
print(s)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
Loading…
Reference in New Issue