def register_api_module(module=None): """Add caller_module to the list of modules which implements apis. The module must have methods: api_XXX which do not collide with other apis. It may also have init_apis(), which will be called unless it is already registered. Args: module (module): defaults to caller module """ assert not _default_route, \ '_init_uris already called. All APIs must registered at init' m = module or pkinspect.caller_module() if m in _api_modules: return # prevent recursion _api_modules.append(m) if hasattr(m, 'init_apis'): m.init_apis() # It's ok if there are no APIs for n, o in inspect.getmembers(m): if n.startswith(_FUNC_PREFIX) and inspect.isfunction(o): assert not n in _api_funcs, \ 'function is duplicate: func={} module={}'.format(n, m.__name__) _api_funcs[n] = o
def all_modules_in_load_path(path_module=None): """Loads all modules in path_module Finds all modules in `cfg.load_path` matching the main_module sans root. If path_module is ``sirepo.pkcli``, then the loaded modules will look like ``<root>.pkcli.<base>``. Only goes one depth. Args: path_module (module): full path module [caller module] Returns: pkcollection.Dict: map of base names to module objects """ import pkgutil _coalesce_values() if not path_module: path_module = pkinspect.caller_module() res = pkcollections.Dict() pn = pkinspect.submodule_name(path_module) for p in reversed(cfg.load_path): try: pm = importlib.import_module(pkinspect.module_name_join((p, pn))) except ImportError: # submodule need not exist in root continue for l, n, is_pkg in pkgutil.iter_modules(path=pm.__path__): if not is_pkg and n not in res: res[n] = importlib.import_module(pkinspect.module_name_join((pm.__name__, n))) return res
def init(**kwargs): """Declares and initializes config params for calling module. Args: kwargs (dict): param name to (default, parser, docstring) Returns: Params: `PKDict` populated with param values """ if '_caller_module' in kwargs: # Internal use only: _values() calls init() to initialize pkconfig.cfg m = kwargs['_caller_module'] del kwargs['_caller_module'] else: if pkinspect.is_caller_main(): print( 'pkconfig.init() called from __main__; cannot configure, ignoring', file=sys.stderr) return None m = pkinspect.caller_module() mnp = m.__name__.split('.') for k in reversed(mnp): kwargs = {k: kwargs} decls = {} _flatten_keys([], kwargs, decls) _coalesce_values() res = PKDict() _iter_decls(decls, res) for k in mnp: res = res[k] return res
def register_login_module(): global login_module m = pkinspect.caller_module() assert not login_module, \ 'login_module already registered: old={} new={}'.format(login_module, m) login_module = m
def init(**kwargs): """Declares and initializes config params for calling module. Args: kwargs (dict): param name to (default, parser, docstring) Returns: Params: `pkcollections.OrderedMapping` populated with param values """ if '_caller_module' in kwargs: # Internal use only: _values() calls init() to initialize pkconfig.cfg m = kwargs['_caller_module'] del kwargs['_caller_module'] else: if pkinspect.is_caller_main(): print( 'pkconfig.init() called from __main__; cannot configure, ignoring', file=sys.stderr) return None m = pkinspect.caller_module() assert pkinspect.root_package(m) in _load_path, \ '{}: module root not in load_path ({})'.format(m.__name__, _load_path) mnp = m.__name__.split('.') for k in reversed(mnp): kwargs = {k: kwargs} decls = {} _flatten_keys([], kwargs, decls) _coalesce_values() res = pkcollections.OrderedMapping() _iter_decls(decls, res) for k in mnp: res = res[k] return res
def i18n_text(text, widget=None, index=None): """Translates text with module as context and optionally sets it Will call `setItemText` or `setText` accordingly on `widget`. Args: text (str): what to translate widget (QWidget): what to set it on index (int): for setItemText Returns: str: Translated text """ res = QtGui.QApplication.translate( pkinspect.caller_module().__name__, text, widget.__class__.__name__ if widget else None, QtGui.QApplication.UnicodeUTF8, ) if widget: if index is not None: widget.setItemText(res) else: widget.setText(res) return res
def load_resource(basename): """Read a resource, making sure all keys and values are locale Args: basename (str): file to read without yml suffix Returns: object: `pkcollections.Dict` or list """ return load_file( pkresource.filename(basename + '.yml', pkinspect.caller_module()))
def render_resource(basename, *args, **kwargs): """Render a pkresource as a jinja template. Args: basename (str): name without jinja extension args (list): see func:`render_file` for rest of args and return """ return render_file( pkresource.filename(basename + '.jinja', pkinspect.caller_module()), *args, **kwargs )
def render_resource(basename, *args, **kwargs): """Render a pkresource as a jinja template. Args: basename (str): name without `RESOURCE_SUFFIX` args (list): see func:`render_file` for rest of args and return """ return render_file( pkresource.filename( basename + RESOURCE_SUFFIX, pkinspect.caller_module(), ), *args, **kwargs)
def template_globals(sim_type=None): """Initializer for templates Usage:: _SIM_DATA, SIM_TYPE, _SCHEMA = sirepo.sim_data.template_globals() Args: sim_type (str): simulation type [calling module's basename] Returns: (class, str, object): SimData class, simulation type, and schema """ c = get_class(sim_type or pkinspect.module_basename(pkinspect.caller_module())) return c, c.sim_type(), c.schema()
def register_api_module(): """Add caller_module to the list of modules which implements apis. The module must have methods: api_XXX which do not collide with other apis. """ m = pkinspect.caller_module() assert not m in _api_modules, \ 'module is a duplicate: module={}'.format(m.__name__) _api_modules.append(m) for n, o in inspect.getmembers(m): if n.startswith(_FUNC_PREFIX) and inspect.isfunction(o): assert not n in _api_funcs, \ 'function is duplicate: func={} module={}'.format(n, m.__name__) _api_funcs[n] = o
def _base_dir(postfix): """Base name with directory. Args: postfix (str): what to append to base (``_data`` or ``_work``). Returns: py.path.local: base directory with postfix """ m = module_under_test or pkinspect.caller_module() filename = py.path.local(m.__file__) b = re.sub(r'_test$|^test_', '', filename.purebasename) assert b != filename.purebasename, \ '{}: module name must end in _test'.format(filename) return py.path.local(filename.dirname).join(b + postfix).realpath()
def filename(relative_filename, caller_context=None): """Return the filename to the resource Args: relative_filename (str): file name relative to package_data directory. caller_context (object): Any object from which to get the `root_package` Returns: str: absolute path of the resource file """ pkg = pkinspect.root_package( caller_context if caller_context else pkinspect.caller_module()) fn = os.path.join(pksetup.PACKAGE_DATA, relative_filename) res = pkg_resources.resource_filename(pkg, fn) if not os.path.exists(res): raise IOError((errno.ENOENT, 'resource does not exist', res)) return res
def filename(relative_filename, caller_context=None): """Return the filename to the resource Args: relative_filename (str): file name relative to package_data directory. caller_context (object): Any object from which to get the `root_package` Returns: str: absolute path of the resource file """ pkg = pkinspect.root_package( caller_context if caller_context else pkinspect.caller_module()) assert not os.path.isabs(relative_filename), \ 'must not be an absolute file name={}'.format(relative_filename) fn = os.path.join(pksetup.PACKAGE_DATA, relative_filename) res = pkg_resources.resource_filename(pkg, fn) if not os.path.exists(res): msg = 'resource does not exist for pkg=' + pkg if pkg == '__main__': msg += '; do not call module as a program' raise IOError((errno.ENOENT, msg, res)) return res
def caller_module(): return pkinspect.caller_module()