Coverage for portality/lib/plugin.py: 49%

51 statements  

« prev     ^ index     » next       coverage.py v6.4.2, created at 2022-07-20 16:12 +0100

1import importlib 

2 

3# Note that we delay import of app to the functions which need it, 

4# since we may want to load plugins during app creation too, and otherwise 

5# we'd get circular import problems 

6 

7class PluginException(Exception): 

8 pass 

9 

10def load_class_raw(classpath): 

11 modpath = ".".join(classpath.split(".")[:-1]) 

12 classname = classpath.split(".")[-1] 

13 try: 

14 mod = importlib.import_module(modpath) 

15 except ImportError: 

16 return None 

17 klazz = getattr(mod, classname, None) 

18 return klazz 

19 

20def load_class(classpath, cache_class_ref=True): 

21 from portality.core import app 

22 klazz = app.config.get("PLUGIN_CLASS_REFS", {}).get(classpath) 

23 if klazz is not None: 

24 return klazz 

25 

26 klazz = load_class_raw(classpath) 

27 if klazz is None: 

28 app.logger.info("Could not load function {x}".format(x=classpath)) 

29 return None 

30 

31 if cache_class_ref: 

32 if "PLUGIN_CLASS_REFS" not in app.config: 

33 app.config["PLUGIN_CLASS_REFS"] = {} 

34 app.config["PLUGIN_CLASS_REFS"][classpath] = klazz 

35 

36 return klazz 

37 

38def load_module(modpath): 

39 return importlib.import_module(modpath) 

40 

41def load_function_raw(fnpath): 

42 modpath = ".".join(fnpath.split(".")[:-1]) 

43 fnname = fnpath.split(".")[-1] 

44 try: 

45 mod = importlib.import_module(modpath) 

46 except ImportError: 

47 return None 

48 fn = getattr(mod, fnname, None) 

49 return fn 

50 

51def load_function(fnpath, cache_fn_ref=True): 

52 from portality.core import app 

53 fn = app.config.get("PLUGIN_FN_REFS", {}).get(fnpath) 

54 if fn is not None: 

55 return fn 

56 

57 fn = load_function_raw(fnpath) 

58 if fn is None: 

59 app.logger.info("Could not load function {x}".format(x=fnpath)) 

60 return None 

61 

62 if cache_fn_ref: 

63 if "PLUGIN_FN_REFS" not in app.config: 

64 app.config["PLUGIN_FN_REFS"] = {} 

65 app.config["PLUGIN_FN_REFS"][fnpath] = fn 

66 

67 return fn