util.py 1.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # coding: utf-8
  2. import importlib
  3. from _elementtree import Element
  4. from opencombat.exception import NotFoundError
  5. __DEFAULT__ = '__DEFAULT__'
  6. def get_class_from_string_path(config, string_path: str) -> type:
  7. """
  8. Return class matching with given path, eg "mymodule.MyClass"
  9. :param config: config object
  10. :param string_path: class path, eg "mymodule.MyClass"
  11. :return: imported class
  12. """
  13. module_address = '.'.join(string_path.split('.')[:-1])
  14. class_name = string_path.split('.')[-1]
  15. module_ = importlib.import_module(module_address)
  16. return getattr(module_, class_name)
  17. def get_text_xml_element(
  18. element: Element,
  19. search_element_name: str,
  20. default_value: str = __DEFAULT__,
  21. ) -> str:
  22. found = element.find(search_element_name)
  23. if found is None:
  24. if default_value == __DEFAULT__:
  25. raise NotFoundError(
  26. 'Asked element "{}" not exist in {}'.format(
  27. search_element_name,
  28. str(element),
  29. ),
  30. )
  31. return default_value
  32. return found.text