github.com/anuvu/tyk@v2.9.0-beta9-dl-apic+incompatible/coprocess/python/tyk/loader.py (about) 1 import imp, sys, os, inspect 2 from gateway import TykGateway as tyk 3 4 class MiddlewareLoader(): 5 def __init__(self, mw=None): 6 self.mw = mw 7 self.bundle_root_path = mw.bundle_root_path 8 9 def is_local_import(self, stack): 10 # Inspect the stack and verify if the "import" call is local (direct call from middleware code) or not: 11 is_local = False 12 for fr in stack: 13 if fr.function != "<module>": 14 continue 15 if self.base_path not in fr.filename: 16 break 17 is_local = True 18 return is_local 19 20 def find_module(self, module_name, package_path): 21 module_filename = "{0}.py".format(module_name) 22 self.base_path = "{0}_{1}".format(self.mw.api_id, self.mw.middleware_id) 23 self.module_path = os.path.join(self.bundle_root_path, self.base_path, module_filename) 24 25 s = inspect.stack() 26 if not self.is_local_import(s): 27 return None 28 29 if not os.path.exists(self.module_path): 30 error_msg = "Your bundle doesn't contain '{0}'".format(module_name) 31 tyk.log(error_msg, "error") 32 return None 33 return self 34 35 def load_module(self, module_name): 36 module = None 37 with open(self.module_path, 'rb') as fp: 38 module = imp.load_module(module_name, fp, self.module_path, ('.py', 'rb', imp.PY_SOURCE)) 39 sys.modules[module_name] = module 40 self.mw.imported_modules.append(module_name) 41 return module