2017-05-18 20:20:11 +02:00
|
|
|
"""
|
|
|
|
lml.utils
|
|
|
|
~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
json utils for dump plugin info class
|
|
|
|
|
2018-06-13 00:52:10 +02:00
|
|
|
:copyright: (c) 2017-2018 by Onni Software Ltd.
|
2017-05-18 20:20:11 +02:00
|
|
|
:license: New BSD License, see LICENSE for more details
|
|
|
|
"""
|
2017-05-18 19:49:48 +02:00
|
|
|
import sys
|
2017-05-18 20:20:11 +02:00
|
|
|
import logging
|
2018-11-05 23:36:27 +01:00
|
|
|
from json import JSONEncoder, dumps
|
2017-05-18 19:49:48 +02:00
|
|
|
|
|
|
|
PY2 = sys.version_info[0] == 2
|
2017-05-18 20:20:11 +02:00
|
|
|
log = logging.getLogger(__name__)
|
2017-05-01 23:18:46 +02:00
|
|
|
|
|
|
|
|
|
|
|
class PythonObjectEncoder(JSONEncoder):
|
2017-05-18 20:20:11 +02:00
|
|
|
"""
|
|
|
|
Custom object encoder for json dump
|
|
|
|
"""
|
2018-08-07 23:24:54 +02:00
|
|
|
|
2017-05-01 23:18:46 +02:00
|
|
|
def default(self, obj):
|
2018-08-07 23:24:54 +02:00
|
|
|
a_list_of_types = (list, dict, str, int, float, bool, type(None))
|
2017-05-01 23:18:46 +02:00
|
|
|
if PY2:
|
|
|
|
a_list_of_types += (unicode,)
|
|
|
|
if isinstance(obj, a_list_of_types):
|
|
|
|
return JSONEncoder.default(self, obj)
|
2018-08-07 23:24:54 +02:00
|
|
|
return {"_python_object": str(obj)}
|
2017-05-01 23:18:46 +02:00
|
|
|
|
|
|
|
|
|
|
|
def json_dumps(keywords):
|
2017-05-18 20:20:11 +02:00
|
|
|
"""
|
|
|
|
Dump function keywords in json
|
|
|
|
"""
|
2017-05-01 23:18:46 +02:00
|
|
|
return dumps(keywords, cls=PythonObjectEncoder)
|
2017-05-18 20:20:11 +02:00
|
|
|
|
|
|
|
|
|
|
|
def do_import(plugin_module_name):
|
|
|
|
"""dynamically import a module"""
|
2018-11-07 08:25:37 +01:00
|
|
|
try:
|
|
|
|
return _do_import(plugin_module_name)
|
|
|
|
except ImportError:
|
|
|
|
log.exception(
|
|
|
|
"%s is abscent or cannot be imported", plugin_module_name
|
|
|
|
)
|
|
|
|
raise
|
2018-11-05 23:32:14 +01:00
|
|
|
|
|
|
|
|
|
|
|
def _do_import(plugin_module_name):
|
|
|
|
plugin_module = __import__(plugin_module_name)
|
|
|
|
if "." in plugin_module_name:
|
|
|
|
modules = plugin_module_name.split(".")
|
|
|
|
for module in modules[1:]:
|
|
|
|
plugin_module = getattr(plugin_module, module)
|
|
|
|
log.debug("found " + plugin_module_name)
|
|
|
|
return plugin_module
|
2017-05-18 20:20:11 +02:00
|
|
|
|
|
|
|
|
|
|
|
def do_import_class(plugin_class):
|
|
|
|
"""dynamically import a class"""
|
|
|
|
try:
|
2018-08-07 23:24:54 +02:00
|
|
|
plugin_module_name = plugin_class.rsplit(".", 1)[0]
|
2017-05-18 20:20:11 +02:00
|
|
|
plugin_module = __import__(plugin_module_name)
|
2018-08-07 23:24:54 +02:00
|
|
|
modules = plugin_class.split(".")
|
2017-05-18 20:20:11 +02:00
|
|
|
for module in modules[1:]:
|
|
|
|
plugin_module = getattr(plugin_module, module)
|
|
|
|
return plugin_module
|
|
|
|
except ImportError:
|
2017-05-19 10:51:54 +02:00
|
|
|
log.exception("Failed to import %s", plugin_module_name)
|
2017-05-18 20:20:11 +02:00
|
|
|
raise
|