Local changes.
[redakcja.git] / apps / apiclient / __init__.py
1 import urllib
2
3 from django.utils import simplejson
4 import oauth2
5
6 from apiclient.models import OAuthConnection
7 from apiclient.settings import WL_CONSUMER_KEY, WL_CONSUMER_SECRET, WL_API_URL
8
9
10 if WL_CONSUMER_KEY and WL_CONSUMER_SECRET:
11     wl_consumer = oauth2.Consumer(WL_CONSUMER_KEY, WL_CONSUMER_SECRET)
12 else:
13     wl_consumer = None
14
15
16 class ApiError(BaseException):
17     pass
18
19
20 class NotAuthorizedError(BaseException):
21     pass
22
23
24 def api_call(user, path, data=None):
25     conn = OAuthConnection.get(user)
26     if not conn.access:
27         raise NotAuthorizedError("No WL authorization for user %s." % user)
28     token = oauth2.Token(conn.token, conn.token_secret)
29     client = oauth2.Client(wl_consumer, token)
30     if data is not None:
31         data = simplejson.dumps(data)
32         data = urllib.urlencode({"data": data})
33         resp, content = client.request(
34                 "%s%s" % (WL_API_URL, path),
35                 method="POST",
36                 body=data)
37     else:
38         resp, content = client.request(
39                 "%s%s" % (WL_API_URL, path))
40     status = resp['status']
41
42     if status == '200':
43         return simplejson.loads(content)
44     elif status.startswith('2'):
45         return
46     elif status == '401':
47         raise ApiError('User not authorized for publishing.')
48     else:
49         raise ApiError("WL API call error %s, path: %s" % (status, path))
50