Commits

pjs  committed 3e696f3

[svn r36] Added restlib

  • Participants
  • Parent commits 1aaf240
  • Branches trunk

Comments (0)

Files changed (1)

+import urllib
+import urllib2
+import httplib
+import hashlib
+import urlparse
+
+
+class APIError(Exception):
+    ''' General exception '''
+    pass
+
+
+class APIClient(object):
+    def __init__(self, url, key, debug=False):
+        url_scheme = urlparse.urlparse(url)
+        self.url = url
+        self.key = key
+        self.scheme = url_scheme.scheme
+        self.host = url_scheme.netloc
+        self.port = url_scheme.port or 80
+        self.path = url_scheme.path
+        self.debug = debug
+
+    def create_hash(self, command):
+        return hashlib.sha1(self.key + command).hexdigest()
+
+    def send_data(self, params, use_hash=False):
+        assert isinstance(params, dict)
+        if use_hash and 'command' in params:
+            params.update({
+                'hash': self.create_hash(params['command']),
+            })
+        
+        return self.send_request(params)
+
+    def send_request(self, request):
+        params = urllib.urlencode(request)
+        if self.debug:
+            print 'DEBUG: ', params
+
+        uop = urllib2.urlopen(self.url, params)
+        code = uop.getcode()
+        data = uop.read()
+        uop.close()
+
+        if code != 200:
+            hash = {'statusmsg': '%i - %s' % (code, uop.msg)}
+            return False, hash
+
+        if data[:2] != 'OK':
+            hash = {
+                'statusmsg': data,
+            }
+            return False, hash
+
+        return True, data