utility.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import json
  2. import datetime
  3. import connectors
  4. import converters
  5. class Utility:
  6. loaded_connector_module = {}
  7. loaded_converter_module = {}
  8. available_connectors = {}
  9. @staticmethod
  10. def import_connector_module(configs):
  11. for config in configs:
  12. module_name = "connectors." + config['connector_module']
  13. class_name = config['connector']
  14. if Utility.loaded_connector_module.get(class_name) is None:
  15. extension_class = getattr(eval(module_name), class_name)
  16. Utility.loaded_connector_module[class_name] = extension_class
  17. return Utility.loaded_connector_module
  18. @staticmethod
  19. def import_converter_module(configs):
  20. for config in configs:
  21. module_name = "converters." + config['converter_module']
  22. class_name = config['converter']
  23. if Utility.loaded_converter_module.get(class_name) is None:
  24. extension_class = getattr(eval(module_name), class_name)
  25. Utility.loaded_converter_module[class_name] = extension_class
  26. return Utility.loaded_converter_module
  27. @staticmethod
  28. def start_connectors(configs):
  29. connectors = Utility.import_connector_module(configs)
  30. converters = Utility.import_converter_module(configs)
  31. for config in configs:
  32. connector_config = config['connector_config']
  33. name = config['station_name']
  34. converter = converters[config['converter']](name)
  35. connector = connectors[config['connector']](name, connector_config, converter)
  36. Utility.available_connectors[name] = connector
  37. connector.open()
  38. @staticmethod
  39. def data_encoder(data_list):
  40. data_json = json.dumps(data_list, cls=DateEncoder)
  41. return data_json
  42. class DateEncoder(json.JSONEncoder):
  43. def default(self, obj):
  44. if isinstance(obj, datetime.datetime):
  45. return obj.strftime("%Y-%m-%d %H:%M:%S")
  46. else:
  47. return json.JSONEncoder.default(self, obj)