On 01/22/2014 02:51 PM, shaohef(a)linux.vnet.ibm.com wrote:
From: ShaoHe Feng <shaohef(a)linux.vnet.ibm.com>
load_url_sub_node can load collections/resouces automatically when they
are tagged with @UrlSubNode
Signed-off-by: ShaoHe Feng <shaohef(a)linux.vnet.ibm.com>
---
src/kimchi/utils.py | 38 ++++++++++++++++++++++++++++++++++++++
1 file changed, 38 insertions(+)
diff --git a/src/kimchi/utils.py b/src/kimchi/utils.py
index 5d6e8ea..94c83d2 100644
--- a/src/kimchi/utils.py
+++ b/src/kimchi/utils.py
@@ -22,6 +22,7 @@
#
import cherrypy
+import imp
I think it should not be there.
import os
import subprocess
import urllib2
@@ -162,3 +163,40 @@ def parse_cmd_output(output, output_items):
res.append(dict(zip(output_items, line.split())))
return res
+
+
+class UrlSubNode(object):
+ def __init__(self, name, auth=False):
+ self.name = name
+ self.auth = auth
+
+ def __call__(self, fun):
+ fun._url_sub_node_name = {"name": self.name}
+ fun.url_auth = self.auth
+ return fun
+
+
+def listPathModules(path):
+ modules = set()
+ for f in os.listdir(path):
+ base, ext = os.path.splitext(f)
+ if ext in ('.py', '.pyc', '.pyo'):
+ modules.add(base)
+ return sorted(modules)
+
+
+def load_url_sub_node(path, package_name, expect_attr="_url_sub_node_name"):
+ sub_nodes = {}
+ for mod_name in listPathModules(path):
+ if mod_name.startswith("_"):
+ continue
+
+ module = import_module(package_name + '.' + mod_name)
+
+ for node in [getattr(module, x) for x in dir(module)]:
+ if not hasattr(node, expect_attr):
+ continue
+ name = getattr(node, expect_attr)["name"]
+ sub_nodes.update({name: node})
+
+ return sub_nodes