-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpyforrst.py
75 lines (56 loc) · 1.7 KB
/
pyforrst.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
"""
pyforrst
========
A thin interface to Forrst API
"""
from urllib import FancyURLopener
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
raise Exception("A JSON parser is required, e.g., simplejson at " \
"http://pypi.python.org/pypi/simplejson/")
version_info = (0, 2)
__version__ = ".".join(map(str, version_info))
_BASE_URI = "http://api.forrst.com/api/v1/"
class ForrstError(Exception):
pass
class ForrstAPIURLOpener(FancyURLopener):
version = 'pyforrst/%s' % (__version__,)
urlopen = ForrstAPIURLOpener().open
def call(url):
"""
Makes a call to Forrst API and handles failed status if so
"""
u = urlopen(_BASE_URI + url)
data = json.loads(u.read())['resp']
if data['stat'] == 'fail':
raise ForrstError("Request failed, reason: %s" % (data['reason'],))
return data
def user_info(username):
"""
Requests user's information by username
"""
response = call("users/info?username=%s" % (username,))
return response['user']
def user_info_by_id(id):
"""
Requests user's information by id
"""
response = call("users/info?id=%d" % (id,))
return response['user']
def user_posts(username, since=None):
"""
Requests user's posts
"""
url = "users/posts?username=%s" % (username,)
if since is not None:
# You could argue the word 'since' isn't exactly intuitively an integer
# so make sure users know it
if not isinstance(since, int):
raise ForrstError("since parameter must be valid id (integer)")
url = url + "&since=%d" % (since,)
response = call(url)
return response['posts']