浏览代码

add new (yet unused) batcave client

Helge Jung 9 年之前
父节点
当前提交
c626664c0d
共有 1 个文件被更改,包括 54 次插入0 次删除
  1. 54 0
      modules/batcave_client.py

+ 54 - 0
modules/batcave_client.py

@@ -0,0 +1,54 @@
+import json
+import logging
+
+from urllib2 import urlopen, URLError
+
+
+class BatcaveClient(object):
+    def __init__(self, base_url):
+        self.base_url = base_url
+        self.logger = logging.getLogger('BATCAVE')
+
+    def __load_response(self, url, error_context):
+        raw_data = None
+        try:
+            raw_data = urlopen(self.base_url + url)
+        except URLError as err:
+            self.logger.error("Failed to contact BATCAVE for %s: %s",
+                              error_context, err)
+            return None
+
+        try:
+            return json.load(raw_data)
+        except ValueError as err:
+            self.logger.error("Could not parse response for %s: %s",
+                              error_context, err)
+            return None
+
+    def get_node(self, nodeid):
+        """Query the given node's data from the BATCAVE."""
+
+        url = 'node/{0}.json'.format(nodeid)
+        return self.__load_response(url, 'node \'' + nodeid + '\'')
+
+    def find_node(self, name, fuzzymatch=True, single_match_only=True):
+        """Tries to find a node by given name."""
+
+        url = 'find?name=' + name + '&fuzzy=' + ('1' if fuzzymatch else '0')
+        matches = self.__load_response(url, 'find=' + name)
+
+        if single_match_only:
+            if len(matches) == 1:
+                return matches[0]
+            else:
+                return None
+
+        return matches
+
+    def get_nodefield(self, nodeid, field):
+        """Query the given field for the given nodeid from the BATCAVE."""
+
+        url = self.base_url + 'node/{0}/{1}'.format(nodeid, field)
+        ctx = "node '{0}'->'{1}'".format(nodeid, field)
+
+        return self.__load_response(url, ctx)