Skip to content

Instantly share code, notes, and snippets.

@timothycrosley
Last active March 31, 2021 20:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save timothycrosley/1669b902f00662e92216 to your computer and use it in GitHub Desktop.
Save timothycrosley/1669b902f00662e92216 to your computer and use it in GitHub Desktop.
Write once run every where
"""An example of writing an API to scrape hacker news once, and then enabling usage everywhere"""
import hug
import requests
@hug.local()
@hug.cli()
@hug.get()
def top_post(section: hug.types.one_of(('news', 'newest', 'show'))='news'):
"""Returns the top post from the provided section"""
content = requests.get('https://news.ycombinator.com/{0}'.format(section)).content
text = content.decode('utf-8')
return text.split('<tr class=\'athing\'>')[1].split("<a href")[1].split(">")[1].split("<")[0]
@kylef000
Copy link

For future reference, line 13: return text.split('<tr class=\'athing\'>')[1].split("<a href")[1].split(">")[1].split("<")[0]

should be changed to:

return text.split('<tr class=\'athing\'')[1].split("<a href")[1].split(">")[1].split("<")[0]

The closing right angle bracket on the tr class causes an error because HN now uses an id for each tr in the style of:
<tr class='athing' id='13228490'>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment