4
0

batcave_client.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import json
  2. import logging
  3. from urllib2 import urlopen, URLError
  4. class BatcaveClient(object):
  5. def __init__(self, base_url):
  6. self.base_url = base_url
  7. self.logger = logging.getLogger('BATCAVE')
  8. def __load_response(self, url, error_context):
  9. raw_data = None
  10. try:
  11. raw_data = urlopen(self.base_url + url)
  12. except URLError as err:
  13. self.logger.error("Failed to contact BATCAVE for %s: %s",
  14. error_context, err)
  15. return None
  16. try:
  17. return json.load(raw_data)
  18. except ValueError as err:
  19. self.logger.error("Could not parse response for %s: %s",
  20. error_context, err)
  21. return None
  22. def get_node(self, nodeid):
  23. """Query the given node's data from the BATCAVE."""
  24. url = 'node/{0}.json'.format(nodeid)
  25. return self.__load_response(url, 'node \'' + nodeid + '\'')
  26. def find_node(self, name, fuzzymatch=True, single_match_only=True):
  27. """Tries to find a node by given name."""
  28. url = 'find?name=' + name + '&fuzzy=' + ('1' if fuzzymatch else '0')
  29. matches = self.__load_response(url, 'find=' + name)
  30. if single_match_only:
  31. if len(matches) == 1:
  32. return matches[0]
  33. else:
  34. return None
  35. return matches
  36. def get_nodefield(self, nodeid, field):
  37. """Query the given field for the given nodeid from the BATCAVE."""
  38. url = self.base_url + 'node/{0}/{1}'.format(nodeid, field)
  39. ctx = "node '{0}'->'{1}'".format(nodeid, field)
  40. return self.__load_response(url, ctx)