util.py 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # coding: utf-8
  2. import importlib
  3. from _elementtree import Element
  4. import xml.dom.minidom as md
  5. from io import StringIO
  6. from opencombat.exception import NotFoundError
  7. __DEFAULT__ = '__DEFAULT__'
  8. def get_class_from_string_path(config, string_path: str) -> type:
  9. """
  10. Return class matching with given path, eg "mymodule.MyClass"
  11. :param config: config object
  12. :param string_path: class path, eg "mymodule.MyClass"
  13. :return: imported class
  14. """
  15. module_address = '.'.join(string_path.split('.')[:-1])
  16. class_name = string_path.split('.')[-1]
  17. module_ = importlib.import_module(module_address)
  18. return getattr(module_, class_name)
  19. def get_text_xml_element(
  20. element: Element,
  21. search_element_name: str,
  22. default_value: str = __DEFAULT__,
  23. ) -> str:
  24. found = element.find(search_element_name)
  25. if found is None:
  26. if default_value == __DEFAULT__:
  27. raise NotFoundError(
  28. 'Asked element "{}" not exist in {}'.format(
  29. search_element_name,
  30. str(element),
  31. ),
  32. )
  33. return default_value
  34. return found.text
  35. def pretty_xml(xml_str):
  36. """
  37. Return a pretty xmlstr of given xml str. Thank's to:
  38. https://gist.github.com/eliask/d8517790b11edac75983d1e6fdab3cab
  39. :param xml_str: ugly xml str
  40. :return: pretty xml str
  41. """
  42. indent = ' ' * 4
  43. return '\n'.join(
  44. line for line in
  45. md.parse(StringIO(xml_str)).toprettyxml(indent=indent).split('\n')
  46. if line.strip()
  47. )