forked from hnrss/hnrss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
75 lines (65 loc) · 2.44 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import requests
class API(object):
base_url = 'https://hn.algolia.com/api/v1'
def __init__(self, points=None, comments=None, link_to='url',
query=None, search_attrs='title', description=True):
self.endpoint = 'search_by_date'
self.params = {}
if points or comments:
numeric_filters = []
if points: numeric_filters.append('points>%s' % points)
if comments: numeric_filters.append('num_comments>%s' % comments)
self.params['numericFilters'] = ','.join(numeric_filters)
if query:
self.params['query'] = '"%s"' % query
if search_attrs != 'default':
self.params['restrictSearchableAttributes'] = search_attrs
self.link_to = link_to
self.description = description
@classmethod
def using_request(cls, request):
return cls(
points = request.args.get('points'),
comments = request.args.get('comments'),
link_to = request.args.get('link', 'url'),
query = request.args.get('q'),
search_attrs = request.args.get('search_attrs', 'title'),
description = bool(int(request.args.get('description', 1))),
)
def _request(self, tags):
params = self.params.copy()
params['tags'] = tags
resp = requests.get(
'%s/%s' % (self.base_url, self.endpoint),
params = params,
verify = False,
)
resp.raise_for_status()
obj = resp.json().copy()
obj.update({
'link_to': self.link_to,
'description': self.description,
})
return obj
def newest(self):
return self._request('(story,poll)')
def ask_hn(self):
return self._request('ask_hn')
def show_hn(self):
return self._request('show_hn')
def polls(self):
return self._request('poll')
def comments(self, story_id=None):
tags = ['comment']
if story_id is not None:
tags.append('story_%s' % story_id)
return self._request(','.join(tags))
def user(self, username, include='all'):
tags = ['author_%s' % username]
if include == 'all':
tags.append('(story,poll,comment)')
elif include == 'submitted':
tags.append('(story,poll)')
elif include == 'threads':
tags.append('comment')
return self._request(','.join(tags))