class MyApp(Application): name = Unicode(u'myapp') running = Bool(False, help="Is the app running?").tag(config=True) classes = List([Bar, Foo]) config_file = Unicode(u'', help="Load this config file").tag(config=True) warn_tpyo = Unicode(u"yes the name is wrong on purpose", config=True, help="Should print a warning if `MyApp.warn-typo=...` command is passed") aliases = Dict({ 'i' : 'Foo.i', 'j' : 'Foo.j', 'name' : 'Foo.name', 'enabled' : 'Bar.enabled', 'log-level' : 'Application.log_level', }) flags = Dict(dict(enable=({'Bar': {'enabled' : True}}, "Set Bar.enabled to True"), disable=({'Bar': {'enabled' : False}}, "Set Bar.enabled to False"), crit=({'Application' : {'log_level' : logging.CRITICAL}}, "set level=CRITICAL"), )) def init_foo(self): self.foo = Foo(parent=self) def init_bar(self): self.bar = Bar(parent=self)
class MyApp(Application): name = Unicode(u'myapp') running = Bool(False, config=True, help="Is the app running?") classes = List([Bar, Foo]) config_file = Unicode(u'', config=True, help="Load this config file") aliases = Dict({ 'i' : 'Foo.i', 'j' : 'Foo.j', 'name' : 'Foo.name', 'enabled' : 'Bar.enabled', 'log-level' : 'Application.log_level', }) flags = Dict(dict(enable=({'Bar': {'enabled' : True}}, "Set Bar.enabled to True"), disable=({'Bar': {'enabled' : False}}, "Set Bar.enabled to False"), crit=({'Application' : {'log_level' : logging.CRITICAL}}, "set level=CRITICAL"), )) def init_foo(self): self.foo = Foo(parent=self) def init_bar(self): self.bar = Bar(parent=self)
class A(Configurable): a = Unicode('default', config=True) b = Unicode('default', config=True) c = Unicode('default', config=True) c_during_config = Unicode('never') @validate('b') def _record_c(self, proposal): # setting b from config records c's value at the time self.c_during_config = self.c return proposal.value
class CrowdDynamicsObject(HasTraits): """Base class for CrowdDynamics simulation objects""" name = Unicode(help='Name for the object. Default to class name.') @default('name') def _default_name(self): return self.__class__.__name__
class Bar(Foo): b = Unicode('gotit', help="The string b.").tag(config=False) c = Float(help="The string c.").tag(config=True) bset = Set([]).tag(config=True, multiplicity='+') bset_values = Set([2,1,5]).tag(config=True, multiplicity='+') bdict = Dict().tag(config=True, multiplicity='+') bdict_values = Dict({1:'a','0':'b',5:'c'}).tag(config=True, multiplicity='+')
class Foo(Configurable): i = Integer(0, help="The integer i.").tag(config=True) j = Integer(1, help="The integer j.").tag(config=True) name = Unicode(u'Brian', help="First name.").tag(config=True) la = List([]).tag(config=True) fdict = Dict().tag(config=True, multiplicity='+')
class FirstUseAuthenticator(Authenticator): """ JupyterHub authenticator that lets users set password on first use. """ dbm_path = Unicode( 'passwords.dbm', config=True, help=""" Path to store the db file with username / pwd hash in """ ) create_users = Bool( True, config=True, help=""" Create users if they do not exist already. When set to false, users would have to be explicitly created before they can log in. Users can be created via the admin panel or by setting whitelist / admin list. """ ) def _user_exists(self, username): """ Return true if given user already exists. Note: Depends on internal details of JupyterHub that might change across versions. Tested with v0.9 """ return self.db.query(User).filter_by(name=username).first() is not None @gen.coroutine def authenticate(self, handler, data): username = data['username'] if not self.create_users: if not self._user_exists(username): return None password = data['password'] with dbm.open(self.dbm_path, 'c', 0o600) as db: stored_pw = db.get(username.encode(), None) if stored_pw is not None: if bcrypt.hashpw(password.encode(), stored_pw) != stored_pw: return None else: db[username] = bcrypt.hashpw(password.encode(), bcrypt.gensalt()) return username def delete_user(self, user): """ When user is deleted, remove their entry from password db. This lets passwords be reset by deleting users. """ with dbm.open(self.dbm_path, 'c', 0o600) as db: del db[user.name]
class Binding(HasTraits): name = Unicode(read_only=True) kernel = Enum(SUPPORTED_KERNELS, default_value=DEFAULT_KERNEL) mime_type = Unicode() connection = Dict() state = Enum( [ BindingState.CONNECTED, BindingState.DISCONNECTED, BindingState.RESTARTED, BindingState.CREATING, BindingState.ERROR, ], default_value=BindingState.DISCONNECTED, ) progress = Dict(default_value={"progress": None, "progress_ratio": None}) def __str__(self): conn_info = [ f" {key}={value}" for key, value in self.connection.items() if value is not None ] return "\n".join([ self.name, f" {self.state}", f" Connection: {self.connection_type}", "\n".join(conn_info), ]) @default("mime_type") def _default_mime_type(self): return MIME_TYPES.get(self.kernel, "unknown") @property def connection_type(self): return self.connection.get("type", BindingConnectionType.SSH) def update_progress(self, message: "str", ratio: "float" = None): self.progress = {"progress": message, "progress_ratio": ratio} def as_dict(self): return { trait: trait_type.get(self) for trait, trait_type in self.traits().items() }
class Foo(HasTraits): number1 = Int() number2 = Int() value = Unicode('Hello') def __init__(self, arg1, **kwargs): self.arg1 = arg1 super(Foo, self).__init__(**kwargs)
class Spark(LoggingConfigurable): """ A config object that is able to replace URLs of the Spark frontend on the fly. """ url = Unicode( 'http://localhost:4040', help='The URL of Spark API', ).tag(config=True) proxy_root = Unicode( '/spark', help='The URL path under which the Spark API will be proxied', ) def __init__(self, *args, **kwargs): self.base_url = kwargs.pop('base_url') super(Spark, self).__init__(*args, **kwargs) self.proxy_url = url_path_join(self.base_url, self.proxy_root) def backend_url(self, request): request_path = request.uri[len(self.proxy_url):] return url_path_join(self.url, request_path) def replace(self, content): """ Replace all the links with our prefixed handler links, e.g.: /proxy/application_1467283586194_0015/static/styles.css' or /static/styles.css with /spark/static/styles.css """ soup = BeautifulSoup(content, BEAUTIFULSOUP_BUILDER) for tags, attribute in PROXY_ATTRIBUTES: for tag in soup.find_all(tags, **{attribute: True}): value = tag[attribute] match = PROXY_PATH_RE.match(value) if match is not None: value = match.groups()[0] tag[attribute] = url_path_join(self.proxy_root, value) return str(soup)
class Bar(Foo): b = Unicode("gotit", help="The string b.").tag(config=False) c = Float(help="The string c.").tag(config=True) bset = Set([]).tag(config=True, multiplicity="+") bset_values = Set([2, 1, 5]).tag(config=True, multiplicity="+") bdict = Dict().tag(config=True, multiplicity="+") bdict_values = Dict({ 1: "a", "0": "b", 5: "c" }).tag(config=True, multiplicity="+")
class BaseJSONConfigManager(LoggingConfigurable): """General JSON config manager Deals with persisting/storing config in a json file """ config_dir = Unicode('.') def ensure_config_dir_exists(self): try: os.makedirs(self.config_dir, 0o755) except OSError as e: if e.errno != errno.EEXIST: raise def file_name(self, section_name): return os.path.join(self.config_dir, section_name + '.json') def get(self, section_name): """Retrieve the config data for the specified section. Returns the data as a dictionary, or an empty dictionary if the file doesn't exist. """ filename = self.file_name(section_name) if os.path.isfile(filename): with io.open(filename, encoding='utf-8') as f: return json.load(f) else: return {} def set(self, section_name, data): """Store the given config data. """ filename = self.file_name(section_name) self.ensure_config_dir_exists() if PY3: f = io.open(filename, 'w', encoding='utf-8') else: f = open(filename, 'wb') with f: json.dump(data, f, indent=2) def update(self, section_name, new_data): """Modify the config section by recursively updating it with new_data. Returns the modified config data as a dictionary. """ data = self.get(section_name) recursive_update(data, new_data) self.set(section_name, data) return data
class Foo(HasTraits): number1 = Int() number2 = Int() value = Unicode('Hello') def __init__(self, arg1, arg2=None, *pos_args, **kw_args): self.arg1 = arg1 self.arg2 = arg2 self.pos_args = pos_args self.kw_args = kw_args super(Foo, self).__init__(*pos_args, **kw_args)
class NotebookGist(LoggingConfigurable): oauth_client_id = Unicode( '', help='The GitHub application OAUTH client ID', ).tag(config=True) oauth_client_secret = Unicode( '', help='The GitHub application OAUTH client secret', ).tag(config=True) def __init__(self, *args, **kwargs): self.config_manager = kwargs.pop('config_manager') super(NotebookGist, self).__init__(*args, **kwargs) # update the frontend settings with the currently passed # OAUTH client id self.config_manager.update( 'notebook', { 'oauth_client_id': self.config.NotebookGist.oauth_client_id, })
class SparkHistory(LoggingConfigurable): """ A config object that is able to replace URLs of the Spark frontend on the fly. """ url = Unicode( 'http://{}:{}'.format(os.getenv('MESOS_CONTAINER_IP', '127.0.0.1'), os.getenv('PORT_SPARKHISTORY', '18080')), help='The URL of Spark History Server', ).tag(config=True) proxy_root = Unicode( '/sparkhistory/', help='The URL path under which the Spark History will be proxied', ) def __init__(self, *args, **kwargs): self.base_url = kwargs.pop('base_url') super(SparkHistory, self).__init__(*args, **kwargs) self.proxy_url = url_path_join(self.base_url, self.proxy_root) def backend_url(self, request): request_path = request.uri[len(self.proxy_url):] return url_path_join(self.url, request_path)
class FirstUseAuthenticator(Authenticator): """ JupyterHub authenticator that lets users set password on first use. """ dbm_path = Unicode('passwords.dbm', config=True, help=""" Path to store the db file with username / pwd hash in """) @gen.coroutine def authenticate(self, handler, data): # Move everything to bytes username = data['username'].encode('utf-8') password = data['password'].encode('utf-8') with dbm.open(self.dbm_path, 'c', 0o600) as db: stored_pw = db.get(username, None) if stored_pw is not None: if bcrypt.hashpw(password, stored_pw) != stored_pw: return None else: db[username] = bcrypt.hashpw(password, bcrypt.gensalt()) return data['username']
class HydraKernelProvisioner(KernelProvisionerBase): subkernel_name = Unicode() poll_interval = Float(1.0) @property def binding(self) -> "Binding": km: "HydraKernelManager" = self.parent assert hasattr(km, "binding") return km.binding async def kill(self, restart: bool = False) -> None: await self.send_signal(int(signal.SIGKILL)) async def terminate(self, restart: bool = False) -> None: await self.send_signal(int(signal.SIGTERM)) async def wait(self) -> "Optional[int]": ret = 0 if self.has_process: while await self.poll() is None: await asyncio.sleep(self.poll_interval) self.reset() return ret async def cleanup(self, restart: bool = False) -> None: """No-op cleanup default implementation to satisfy base class.""" pass def reset(self) -> None: """Reset the has_process state. In general, this function should modify the state of the provisioner such that has_process returns false. """ pass
class CookaApp(Application): server_port = Integer(8000).tag(config=True) language = Unicode("use_client").tag(config=True) data_directory = Unicode("~/cooka").tag(config=True) notebook_portal = Unicode(_get_default_notebook_portal()).tag(config=True) optimize_metric = Dict( per_key_traits={ "multi_classification_optimize": Unicode("accuracy").tag(config=True), "binary_classification": Unicode("auc").tag(config=True), "regression": Unicode("rmse").tag(config=True) } ).tag(config=True) max_trials = Dict( per_key_traits={ "performance": Integer(50), "quick": Integer(10), "minimal": Integer(1) } ).tag(config=True)
class BodyType(Body): body_type = Unicode(help='Selected body type') body_types = Instance(ConfigObj, help='Mapping of body type names to values') # Ratios of radii for shoulders and torso ratio_rt = Float(default_value=0, min=0, max=1, help='Ratio between total radius and torso radius') ratio_rs = Float(default_value=0, min=0, max=1, help='Ratio between total radius and shoulder radius') ratio_ts = Float( default_value=0, min=0, max=1, help='Ratio between total radius and distance from torso to shoulder') # Scales for settings values from truncated normal distribution # TODO: Distributions class as instance traits radius_mean = Float(default_value=0, min=0) radius_scale = Float(default_value=0, min=0) target_velocity_mean = Float(default_value=0, min=0) target_velocity_scale = Float(default_value=0, min=0) mass_mean = Float(default_value=0, min=0) mass_scale = Float(default_value=0, min=0) @staticmethod def _truncnorm(mean, abs_scale): """Individual value from truncnorm""" return np.asscalar(truncnorm(-3.0, 3.0, loc=mean, abs_scale=abs_scale)) @default('body_types') def _default_body_types(self): return load_config(BODY_TYPES_CFG, BODY_TYPES_CFG_SPEC) @observe('body_type') def _observe_body_type(self, change): if change['old'] == '': new = change['new'] for k, v in self.body_types[new].items(): setattr(self, k, v) else: raise TraitError('Body type can only be set once.') @observe('radius_mean', 'radius_scale') def _observe_radius_truncnorm(self, change): if self.radius == 0 and self.radius_mean > 0 and self.radius_scale > 0: self.radius = self._truncnorm(self.radius_mean, self.radius_scale) @observe('radius', 'ratio_rt', 'ratio_rs', 'ratio_ts') def _observe_radius(self, change): """Set torso radius if ratio_rt changes and radius is defined or if radius changes and ratio_rt is defined.""" name = change['name'] if name == 'radius': if self.ratio_rt > 0: self.r_t = self.ratio_rt * self.radius if self.ratio_rs > 0: self.r_s = self.ratio_rs * self.radius if self.ratio_ts > 0: self.r_ts = self.ratio_ts * self.radius elif self.radius > 0: if name == 'ratio_rt': self.r_t = self.ratio_rt * self.radius elif name == 'ratio_rs': self.r_s = self.ratio_rs * self.radius elif name == 'ratio_ts': self.r_ts = self.ratio_ts * self.radius @observe('mass_mean', 'mass_scale') def _observe_mass_truncnorm(self, change): if self.mass == 0 and self.mass_mean > 0 and self.mass_scale > 0: self.mass = self._truncnorm(self.mass_mean, self.mass_scale) @observe('target_velocity_mean', 'target_velocity_scale') def _observe_target_velocity_truncnorm(self, change): if self.target_velocity == 0 and self.target_velocity_mean > 0 and self.target_velocity_scale > 0: self.target_velocity = self._truncnorm(self.target_velocity_mean, self.target_velocity_scale) @observe('mass', 'radius') def _observe_inertia_rot(self, change): if self.inertia_rot == 0 and self.mass > 0 and self.radius > 0: inertia = 4.0 * np.pi mass = 80.0 radius = 0.27 self.inertia_rot = inertia * (self.mass / mass) * (self.radius / radius)**2
class Foo(HasTraits): number1 = Int() number2 = Int() value = Unicode('Hello')
class Foo(Configurable): a = Integer(0, help="The integer a.").tag(config=True) b = Unicode('nope').tag(config=True) flist = List([]).tag(config=True) fdict = Dict().tag(config=True)
class MyConfigurable(Configurable): a = Integer(1, help="The integer a.").tag(config=True) b = Float(1.0, help="The integer b.").tag(config=True) c = Unicode('no config')
class Bar(Foo): b = Unicode('gotit', help="The string b.").tag(config=False) c = Float(help="The string c.").tag(config=True) bset = Set([]).tag(config=True, multiplicity='+') bdict = Dict().tag(config=True, multiplicity='+')
class Bar(Foo): b = Unicode('gotit', help="The string b.").tag(config=False) c = Float(help="The string c.").tag(config=True)
class Foo(Configurable): i = Integer(0, help="The integer i.").tag(config=True) j = Integer(1, help="The integer j.").tag(config=True) name = Unicode(u'Brian', help="First name.").tag(config=True)
class TestApp(Application): value = Unicode().tag(config=True) config_file_loaded = Bool().tag(config=True) aliases = {'v': 'TestApp.value'}
class Application(SingletonConfigurable): """A singleton application with full configuration support.""" # The name of the application, will usually match the name of the command # line application name = Unicode('application') # The description of the application that is printed at the beginning # of the help. description = Unicode('This is an application.') # default section descriptions option_description = Unicode(option_description) keyvalue_description = Unicode(keyvalue_description) subcommand_description = Unicode(subcommand_description) python_config_loader_class = PyFileConfigLoader json_config_loader_class = JSONFileConfigLoader # The usage and example string that goes at the end of the help string. examples = Unicode() # A sequence of Configurable subclasses whose config=True attributes will # be exposed at the command line. classes = [] def _classes_inc_parents(self, classes=None): """Iterate through configurable classes, including configurable parents :param classes: The list of classes to iterate; if not set, uses :attr:`classes`. Children should always be after parents, and each class should only be yielded once. """ if classes is None: classes = self.classes seen = set() for c in classes: # We want to sort parents before children, so we reverse the MRO for parent in reversed(c.mro()): if issubclass(parent, Configurable) and (parent not in seen): seen.add(parent) yield parent # The version string of this application. version = Unicode('0.0') # the argv used to initialize the application argv = List() # Whether failing to load config files should prevent startup raise_config_file_errors = Bool( TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR) # The log level for the application log_level = Enum( (0, 10, 20, 30, 40, 50, 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL'), default_value=logging.WARN, help="Set the log level by value or name.").tag(config=True) @observe('log_level') @observe_compat def _log_level_changed(self, change): """Adjust the log level when log_level is set.""" new = change.new if isinstance(new, str): new = getattr(logging, new) self.log_level = new self.log.setLevel(new) _log_formatter_cls = LevelFormatter log_datefmt = Unicode( "%Y-%m-%d %H:%M:%S", help="The date format used by logging formatters for %(asctime)s").tag( config=True) log_format = Unicode( "[%(name)s]%(highlevel)s %(message)s", help="The Logging format template", ).tag(config=True) @observe('log_datefmt', 'log_format') @observe_compat def _log_format_changed(self, change): """Change the log formatter when log_format is set.""" _log_handler = self._get_log_handler() if not _log_handler: warnings.warn( "No Handler found on {self.log}, setting log_format will have no effect", RuntimeWarning, ) return _log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt) _log_handler.setFormatter(_log_formatter) @default('log') def _log_default(self): """Start logging for this application. The default is to log to stderr using a StreamHandler, if no default handler already exists. The log level starts at logging.WARN, but this can be adjusted by setting the ``log_level`` attribute. """ log = logging.getLogger(self.__class__.__name__) log.setLevel(self.log_level) log.propagate = False _log = log # copied from Logger.hasHandlers() (new in Python 3.2) while _log: if _log.handlers: return log if not _log.propagate: break else: _log = _log.parent if sys.executable and sys.executable.endswith('pythonw.exe'): # this should really go to a file, but file-logging is only # hooked up in parallel applications _log_handler = logging.StreamHandler(open(os.devnull, 'w')) else: _log_handler = logging.StreamHandler() _log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt) _log_handler.setFormatter(_log_formatter) log.addHandler(_log_handler) return log #: the alias map for configurables #: Keys might strings or tuples for additional options; single-letter alias accessed like `-v`. #: Values might be like "Class.trait" strings of two-tuples: (Class.trait, help-text). aliases = {'log-level': 'Application.log_level'} # flags for loading Configurables or store_const style flags # flags are loaded from this dict by '--key' flags # this must be a dict of two-tuples, the first element being the Config/dict # and the second being the help string for the flag flags = { 'debug': ({ 'Application': { 'log_level': logging.DEBUG, }, }, "Set log-level to debug, for the most verbose logging."), 'show-config': ({ 'Application': { 'show_config': True, }, }, "Show the application's configuration (human-readable format)"), 'show-config-json': ({ 'Application': { 'show_config_json': True, }, }, "Show the application's configuration (json format)"), } # subcommands for launching other applications # if this is not empty, this will be a parent Application # this must be a dict of two-tuples, # the first element being the application class/import string # and the second being the help string for the subcommand subcommands = Dict() # parse_command_line will initialize a subapp, if requested subapp = Instance('traitlets.config.application.Application', allow_none=True) # extra command-line arguments that don't set config values extra_args = List(Unicode()) cli_config = Instance( Config, (), {}, help="""The subset of our configuration that came from the command-line We re-load this configuration after loading config files, to ensure that it maintains highest priority. """) _loaded_config_files = List() show_config = Bool( help="Instead of starting the Application, dump configuration to stdout" ).tag(config=True) show_config_json = Bool( help= "Instead of starting the Application, dump configuration to stdout (as JSON)" ).tag(config=True) @observe('show_config_json') def _show_config_json_changed(self, change): self.show_config = change.new @observe('show_config') def _show_config_changed(self, change): if change.new: self._save_start = self.start self.start = self.start_show_config def __init__(self, **kwargs): SingletonConfigurable.__init__(self, **kwargs) # Ensure my class is in self.classes, so my attributes appear in command line # options and config files. cls = self.__class__ if cls not in self.classes: if self.classes is cls.classes: # class attr, assign instead of insert self.classes = [cls] + self.classes else: self.classes.insert(0, self.__class__) @observe('config') @observe_compat def _config_changed(self, change): super(Application, self)._config_changed(change) self.log.debug('Config changed: %r', change.new) @catch_config_error def initialize(self, argv=None): """Do the basic steps to configure me. Override in subclasses. """ self.parse_command_line(argv) def start(self): """Start the app mainloop. Override in subclasses. """ if self.subapp is not None: return self.subapp.start() def start_show_config(self): """start function used when show_config is True""" config = self.config.copy() # exclude show_config flags from displayed config for cls in self.__class__.mro(): if cls.__name__ in config: cls_config = config[cls.__name__] cls_config.pop('show_config', None) cls_config.pop('show_config_json', None) if self.show_config_json: json.dump(config, sys.stdout, indent=1, sort_keys=True, default=repr) # add trailing newline sys.stdout.write('\n') return if self._loaded_config_files: print("Loaded config files:") for f in self._loaded_config_files: print(' ' + f) print() for classname in sorted(config): class_config = config[classname] if not class_config: continue print(classname) pformat_kwargs = dict(indent=4, compact=True) for traitname in sorted(class_config): value = class_config[traitname] print(' .{} = {}'.format( traitname, pprint.pformat(value, **pformat_kwargs), )) def print_alias_help(self): """Print the alias parts of the help.""" print('\n'.join(self.emit_alias_help())) def emit_alias_help(self): """Yield the lines for alias part of the help.""" if not self.aliases: return classdict = {} for cls in self.classes: # include all parents (up to, but excluding Configurable) in available names for c in cls.mro()[:-3]: classdict[c.__name__] = c for alias, longname in self.aliases.items(): try: if isinstance(longname, tuple): longname, fhelp = longname else: fhelp = None classname, traitname = longname.split('.', 1) cls = classdict[classname] trait = cls.class_traits(config=True)[traitname] fhelp = cls.class_get_trait_help(trait, helptext=fhelp).splitlines() if not isinstance(alias, tuple): alias = (alias, ) alias = sorted(alias, key=len) alias = ', '.join( ('--%s' if len(m) > 1 else '-%s') % m for m in alias) # reformat first line fhelp[0] = fhelp[0].replace('--' + longname, alias) for l in fhelp: yield l yield indent("Equivalent to: [--%s]" % longname) except Exception as ex: self.log.error( 'Failed collecting help-message for alias %r, due to: %s', alias, ex) raise def print_flag_help(self): """Print the flag part of the help.""" print('\n'.join(self.emit_flag_help())) def emit_flag_help(self): """Yield the lines for the flag part of the help.""" if not self.flags: return for flags, (cfg, fhelp) in self.flags.items(): try: if not isinstance(flags, tuple): flags = (flags, ) flags = sorted(flags, key=len) flags = ', '.join( ('--%s' if len(m) > 1 else '-%s') % m for m in flags) yield flags yield indent(dedent(fhelp.strip())) cfg_list = ' '.join('--%s.%s=%s' % (clname, prop, val) for clname, props_dict in cfg.items() for prop, val in props_dict.items()) cfg_txt = "Equivalent to: [%s]" % cfg_list yield indent(dedent(cfg_txt)) except Exception as ex: self.log.error( 'Failed collecting help-message for flag %r, due to: %s', flags, ex) raise def print_options(self): """Print the options part of the help.""" print('\n'.join(self.emit_options_help())) def emit_options_help(self): """Yield the lines for the options part of the help.""" if not self.flags and not self.aliases: return header = 'Options' yield header yield '=' * len(header) for p in wrap_paragraphs(self.option_description): yield p yield '' for l in self.emit_flag_help(): yield l for l in self.emit_alias_help(): yield l yield '' def print_subcommands(self): """Print the subcommand part of the help.""" print('\n'.join(self.emit_subcommands_help())) def emit_subcommands_help(self): """Yield the lines for the subcommand part of the help.""" if not self.subcommands: return header = "Subcommands" yield header yield '=' * len(header) for p in wrap_paragraphs( self.subcommand_description.format(app=self.name)): yield p yield '' for subc, (cls, help) in self.subcommands.items(): yield subc if help: yield indent(dedent(help.strip())) yield '' def emit_help_epilogue(self, classes): """Yield the very bottom lines of the help message. If classes=False (the default), print `--help-all` msg. """ if not classes: yield "To see all available configurables, use `--help-all`." yield '' def print_help(self, classes=False): """Print the help for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed. """ print('\n'.join(self.emit_help(classes=classes))) def emit_help(self, classes=False): """Yield the help-lines for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed. """ for l in self.emit_description(): yield l for l in self.emit_subcommands_help(): yield l for l in self.emit_options_help(): yield l if classes: help_classes = self._classes_with_config_traits() if help_classes: yield "Class options" yield "=============" for p in wrap_paragraphs(self.keyvalue_description): yield p yield '' for cls in help_classes: yield cls.class_get_help() yield '' for l in self.emit_examples(): yield l for l in self.emit_help_epilogue(classes): yield l def document_config_options(self): """Generate rST format documentation for the config options this application Returns a multiline string. """ return '\n'.join(c.class_config_rst_doc() for c in self._classes_inc_parents()) def print_description(self): """Print the application description.""" print('\n'.join(self.emit_description())) def emit_description(self): """Yield lines with the application description.""" for p in wrap_paragraphs(self.description or self.__doc__): yield p yield '' def print_examples(self): """Print usage and examples (see `emit_examples()`). """ print('\n'.join(self.emit_examples())) def emit_examples(self): """Yield lines with the usage and examples. This usage string goes at the end of the command line help string and should contain examples of the application's usage. """ if self.examples: yield "Examples" yield "--------" yield '' yield indent(dedent(self.examples.strip())) yield '' def print_version(self): """Print the version string.""" print(self.version) @catch_config_error def initialize_subcommand(self, subc, argv=None): """Initialize a subcommand with argv.""" subapp, _ = self.subcommands.get(subc) if isinstance(subapp, str): subapp = import_item(subapp) ## Cannot issubclass() on a non-type (SOhttp://stackoverflow.com/questions/8692430) if isinstance(subapp, type) and issubclass(subapp, Application): # Clear existing instances before... self.__class__.clear_instance() # instantiating subapp... self.subapp = subapp.instance(parent=self) elif callable(subapp): # or ask factory to create it... self.subapp = subapp(self) else: raise AssertionError("Invalid mappings for subcommand '%s'!" % subc) # ... and finally initialize subapp. self.subapp.initialize(argv) def flatten_flags(self): """Flatten flags and aliases for loaders, so cl-args override as expected. This prevents issues such as an alias pointing to InteractiveShell, but a config file setting the same trait in TerminalInteraciveShell getting inappropriate priority over the command-line arg. Also, loaders expect ``(key: longname)`` and not ````key: (longname, help)`` items. Only aliases with exactly one descendent in the class list will be promoted. """ # build a tree of classes in our list that inherit from a particular # it will be a dict by parent classname of classes in our list # that are descendents mro_tree = defaultdict(list) for cls in self.classes: clsname = cls.__name__ for parent in cls.mro()[1:-3]: # exclude cls itself and Configurable,HasTraits,object mro_tree[parent.__name__].append(clsname) # flatten aliases, which have the form: # { 'alias' : 'Class.trait' } aliases = {} for alias, longname in self.aliases.items(): if isinstance(longname, tuple): longname, _ = longname cls, trait = longname.split('.', 1) children = mro_tree[cls] if len(children) == 1: # exactly one descendent, promote alias cls = children[0] if not isinstance(aliases, tuple): alias = (alias, ) for al in alias: aliases[al] = '.'.join([cls, trait]) # flatten flags, which are of the form: # { 'key' : ({'Cls' : {'trait' : value}}, 'help')} flags = {} for key, (flagdict, help) in self.flags.items(): newflag = {} for cls, subdict in flagdict.items(): children = mro_tree[cls] # exactly one descendent, promote flag section if len(children) == 1: cls = children[0] if cls in newflag: newflag[cls].update(subdict) else: newflag[cls] = subdict if not isinstance(key, tuple): key = (key, ) for k in key: flags[k] = (newflag, help) return flags, aliases def _create_loader(self, argv, aliases, flags, classes): return KVArgParseConfigLoader(argv, aliases, flags, classes=classes, log=self.log) @catch_config_error def parse_command_line(self, argv=None): """Parse the command line arguments.""" assert not isinstance(argv, str) argv = sys.argv[1:] if argv is None else argv self.argv = [cast_unicode(arg) for arg in argv] if argv and argv[0] == 'help': # turn `ipython help notebook` into `ipython notebook -h` argv = argv[1:] + ['-h'] if self.subcommands and len(argv) > 0: # we have subcommands, and one may have been specified subc, subargv = argv[0], argv[1:] if re.match(r'^\w(\-?\w)*$', subc) and subc in self.subcommands: # it's a subcommand, and *not* a flag or class parameter return self.initialize_subcommand(subc, subargv) # Arguments after a '--' argument are for the script IPython may be # about to run, not IPython iteslf. For arguments parsed here (help and # version), we want to only search the arguments up to the first # occurrence of '--', which we're calling interpreted_argv. try: interpreted_argv = argv[:argv.index('--')] except ValueError: interpreted_argv = argv if any(x in interpreted_argv for x in ('-h', '--help-all', '--help')): self.print_help('--help-all' in interpreted_argv) self.exit(0) if '--version' in interpreted_argv or '-V' in interpreted_argv: self.print_version() self.exit(0) # flatten flags&aliases, so cl-args get appropriate priority: flags, aliases = self.flatten_flags() classes = tuple(self._classes_with_config_traits()) loader = self._create_loader(argv, aliases, flags, classes=classes) try: self.cli_config = deepcopy(loader.load_config()) except SystemExit: # traitlets 5: no longer print help output on error # help output is huge, and comes after the error raise self.update_config(self.cli_config) # store unparsed args in extra_args self.extra_args = loader.extra_args @classmethod def _load_config_files(cls, basefilename, path=None, log=None, raise_config_file_errors=False): """Load config files (py,json) by filename and path. yield each config object in turn. """ if not isinstance(path, list): path = [path] for path in path[::-1]: # path list is in descending priority order, so load files backwards: pyloader = cls.python_config_loader_class(basefilename + '.py', path=path, log=log) if log: log.debug("Looking for %s in %s", basefilename, path or os.getcwd()) jsonloader = cls.json_config_loader_class(basefilename + '.json', path=path, log=log) loaded = [] filenames = [] for loader in [pyloader, jsonloader]: config = None try: config = loader.load_config() except ConfigFileNotFound: pass except Exception: # try to get the full filename, but it will be empty in the # unlikely event that the error raised before filefind finished filename = loader.full_filename or basefilename # problem while running the file if raise_config_file_errors: raise if log: log.error("Exception while loading config file %s", filename, exc_info=True) else: if log: log.debug("Loaded config file: %s", loader.full_filename) if config: for filename, earlier_config in zip(filenames, loaded): collisions = earlier_config.collisions(config) if collisions and log: log.warning( "Collisions detected in {0} and {1} config files." " {1} has higher priority: {2}".format( filename, loader.full_filename, json.dumps(collisions, indent=2), )) yield (config, loader.full_filename) loaded.append(config) filenames.append(loader.full_filename) @property def loaded_config_files(self): """Currently loaded configuration files""" return self._loaded_config_files[:] @catch_config_error def load_config_file(self, filename, path=None): """Load config files by filename and path.""" filename, ext = os.path.splitext(filename) new_config = Config() for (config, filename) in self._load_config_files( filename, path=path, log=self.log, raise_config_file_errors=self.raise_config_file_errors, ): new_config.merge(config) if filename not in self._loaded_config_files: # only add to list of loaded files if not previously loaded self._loaded_config_files.append(filename) # add self.cli_config to preserve CLI config priority new_config.merge(self.cli_config) self.update_config(new_config) def _classes_with_config_traits(self, classes=None): """ Yields only classes with configurable traits, and their subclasses. :param classes: The list of classes to iterate; if not set, uses :attr:`classes`. Thus, produced sample config-file will contain all classes on which a trait-value may be overridden: - either on the class owning the trait, - or on its subclasses, even if those subclasses do not define any traits themselves. """ if classes is None: classes = self.classes cls_to_config = OrderedDict( (cls, bool(cls.class_own_traits(config=True))) for cls in self._classes_inc_parents(classes)) def is_any_parent_included(cls): return any(b in cls_to_config and cls_to_config[b] for b in cls.__bases__) ## Mark "empty" classes for inclusion if their parents own-traits, # and loop until no more classes gets marked. # while True: to_incl_orig = cls_to_config.copy() cls_to_config = OrderedDict( (cls, inc_yes or is_any_parent_included(cls)) for cls, inc_yes in cls_to_config.items()) if cls_to_config == to_incl_orig: break for cl, inc_yes in cls_to_config.items(): if inc_yes: yield cl def generate_config_file(self, classes=None): """generate default config file from Configurables""" lines = ["# Configuration file for %s." % self.name] lines.append('') classes = self.classes if classes is None else classes config_classes = list(self._classes_with_config_traits(classes)) for cls in config_classes: lines.append(cls.class_config_section(config_classes)) return '\n'.join(lines) def exit(self, exit_status=0): self.log.debug("Exiting application: %s" % self.name) sys.exit(exit_status) @classmethod def launch_instance(cls, argv=None, **kwargs): """Launch a global instance of this Application If a global instance already exists, this reinitializes and starts it """ app = cls.instance(**kwargs) app.initialize(argv) app.start()
class KBaseWSManager(KBaseWSManagerMixin, ContentsManager): """ A notebook manager that uses the KBase workspace for storage. The Workspace backend simply adds a few metadata fields into the notebook object and pushes it into the workspace as the 'data' part of a workspace object Additional metadata fields { 'id' : User specified title for the narrative alphanumeric + _ 'creator' : {username of the creator of this notebook}, 'description' : 'description of notebook', 'data_dependencies' : { list of kbase id strings } 'format' : self.node_format 'workspace' : the workspace that it was loaded from or saved to } This handler expects that on every request, the session attribute for an instance will be populated by the front end handlers. That's gross, but that's what we're running with for now. Note: you'll probably see "That's gross, but..." a lot in this rev of the code Notebooks are identified with workspace identifiers of the format {workspace_name}.{object_name} Object format: (New) { 'dependencies' : List of workspace refs, 'notebook' : { <mostly, the IPython notebook object>, 'metadata' : } } """ kbasews_uri = Unicode(URLS.workspace, config=True, help='Workspace service endpoint URI') ipynb_type = Unicode('ipynb') allowed_formats = List(['json']) node_format = ipynb_type ws_type = Unicode('KBaseNarrative.Narrative', config=True, help='Type to store narratives within workspace service') # regex for parsing out workspace_id and object_id from # a "ws.{workspace}.{object}" string # should accept any of the following formats (the numbers are just random): # ws.123.obj.456.ver.789 # ws.123.obj.456 # ws.123 # 123 path_regex = re.compile('^(ws\.)?(?P<wsid>\d+)((\.obj\.(?P<objid>\d+))(\.ver\.(?P<ver>\d+))?)?$') # This is a regular expression to make sure that the workspace ID # doesn't contain non-legit characters in the object ID field # We use it like this to to translate names: # wsid_regex.sub('',"Hello! Freaking World! 123".replace(' ','_')) # to get an id of 'Hello_Freaking_World_123' # We will enforce validation on the narrative naming GUI, but this is # a safety net wsid_regex = re.compile('[\W]+', re.UNICODE) def __init__(self, *args, **kwargs): """Verify that we can connect to the configured WS instance""" super(KBaseWSManager, self).__init__(*args, **kwargs) if not self.kbasews_uri: raise HTTPError(412, "Missing KBase workspace service endpoint URI.") # Init the session info we need. self.narrative_logger = get_narrative_logger() self.user_service = UserService() def _checkpoints_class_default(self): return KBaseCheckpoints def get_userid(self): """Return the current user id (if logged in), or None """ return util.kbase_env.user def _clean_id(self, id): """Clean any whitespace out of the given id""" return self.wsid_regex.sub('', id.replace(' ', '_')) ##### # API part 1: methods that must be implemented in subclasses. ##### def dir_exists(self, path): """If it's blank, just return True - we'll be looking up the list of all Narratives from that dir, so it's real.""" if not path: return True else: return False def is_hidden(self, path): """We can only see what gets returned from Workspace lookup, so nothing should be hidden""" return False def file_exists(self, path): """We only support narratives right now, so look up a narrative from that path.""" ref = self._parse_path(path) self.log.warn('looking up whether a narrative exists') try: self.log.warn('trying to get narrative {}'.format(ref)) return self.narrative_exists(ref) except WorkspaceError as err: self.log.warn("Error while testing narrative existence: {}".format(str(err))) if err.http_code == 403: raise HTTPError(403, "You do not have permission to view the narrative with id {}".format(path)) else: raise HTTPError(err.http_code, "An error occurred while trying to find the Narrative with id {}".format(path)) def exists(self, path): """Looks up whether a directory or file path (i.e. narrative) exists""" path = path.strip('/') if not path: # it's a directory, for all narratives return True return self.file_exists(path) def _wsobj_to_model(self, nar, content=True): nar_id = 'ws.{}.obj.{}'.format(nar['wsid'], nar['objid']) model = base_model('{} - {} - {}'.format(nar['saved_by'], nar_id, nar['name']), nar_id) model['format'] = 'json' model['last_modified'] = nar['save_date'] model['type'] = 'notebook' return model def _parse_path(self, path): """ From the URL path for a Narrative, returns a NarrativeRef if the path isn't parseable, this raises a 404 with the invalid path. """ path = path.strip('/') m = self.path_regex.match(path) if m is None: raise HTTPError(404, "Invalid Narrative path {}".format(path)) try: return NarrativeRef(dict( wsid=m.group('wsid'), objid=m.group('objid'), ver=m.group('ver') )) except RuntimeError as e: raise HTTPError(500, str(e)) except WorkspaceError as e: raise HTTPError(e.http_code, e.message) def get(self, path, content=True, type=None, format=None): """Get the model of a file or directory with or without content.""" path = path.strip('/') model = base_model(path, path) try: if self.exists(path) and type != 'directory': #It's a narrative object, so try to fetch it. ref = self._parse_path(path) if not ref: raise HTTPError(404, 'Unknown Narrative "{}"'.format(path)) nar_obj = self.read_narrative(ref, content=content) model['type'] = 'notebook' user = self.get_userid() if content: model['format'] = 'json' nb = nbformat.reads(json.dumps(nar_obj['data']), 4) nb['metadata'].pop('orig_nbformat', None) self.mark_trusted_cells(nb, nar_obj['info'][5], path) model['content'] = nb model['name'] = nar_obj['data']['metadata'].get('name', 'Untitled') util.kbase_env.narrative = 'ws.{}.obj.{}'.format(ref.wsid, ref.objid) util.kbase_env.workspace = model['content'].metadata.ws_name self.narrative_logger.narrative_open('{}/{}'.format(ref.wsid, ref.objid), nar_obj['info'][4]) if user is not None: model['writable'] = self.narrative_writable(ref, user) self.log.info('Got narrative {}'.format(model['name'])) except WorkspaceError as e: raise HTTPError(e.http_code, e.message) if not path or type == 'directory': #if it's the empty string, look up all narratives, treat them as a dir self.log.info('Getting narrative list') model['type'] = type model['format'] = 'json' if content: contents = [] nar_list = self.list_narratives() self.log.info('Found {} narratives'.format(len(nar_list))) for nar in nar_list: contents.append(self._wsobj_to_model(nar, content=False)) model['content'] = contents return model def save(self, model, path): """Save the file or directory and return the model with no content. Save implementations should call self.run_pre_save_hook(model=model, path=path) prior to writing any data. """ path = path.strip('/') if 'type' not in model: raise HTTPError(400, 'No IPython model type provided') if model['type'] != 'notebook': raise HTTPError(400, 'We currently only support saving Narratives!') if 'content' not in model and model['type'] != 'directory': raise HTTPError(400, 'No Narrative content found while trying to save') self.log.debug("writing Narrative %s." % path) nb = nbformat.from_dict(model['content']) self.check_and_sign(nb, path) try: ref = self._parse_path(path) result = self.write_narrative(ref, nb, self.get_userid()) new_id = "ws.%s.obj.%s" % (result[1], result[2]) util.kbase_env.narrative = new_id nb = result[0] self.validate_notebook_model(model) validation_message = model.get('message', None) model = self.get(path, content=False) if validation_message: model['message'] = validation_message self.narrative_logger.narrative_save('{}/{}'.format(result[1], result[2]), result[3]) return model except WorkspaceError as err: raise HTTPError(err.http_code, "While saving your Narrative: {}".format(err.message)) def delete_file(self, path): """Delete file or directory by path.""" raise HTTPError(501, 'Narrative deletion not implemented here. Deletion is handled elsewhere.') def rename_file(self, path, new_name): """Rename a file from old_path to new_path. This gets tricky in KBase since we don't deal with paths, but with actual file names. For now, assume that 'old_path' won't actually change, but the 'new_path' is actually the new Narrative name.""" try: self.rename_narrative(self._parse_path(path), self.get_userid(), new_name) except WorkspaceError as err: raise HTTPError(err.http_code, err.message) except Exception as err: raise HTTPError(500, 'An error occurred while renaming your Narrative: {}'.format(err)) # API part 2: methods that have useable default # implementations, but can be overridden in subclasses. def delete(self, path): """Delete a file/directory and any associated checkpoints.""" path = path.strip('/') if not path: raise HTTPError(400, "Can't delete root") self.delete_file(path) self.checkpoints.delete_all_checkpoints(path) def rename(self, old_path, new_path): """Rename a file and any checkpoints associated with that file.""" self.rename_file(old_path, new_path) self.checkpoints.rename_all_checkpoints(old_path, new_path) def update(self, model, path): """Update the file's path For use in PATCH requests, to enable renaming a file without re-uploading its contents. Only used for renaming at the moment. """ self.log.warn('update') self.log.warn(model) self.log.warn(path) path = path.strip('/') new_path = model.get('path', path).strip('/') if new_path.endswith('.ipynb'): new_path = new_path[:-len('.ipynb')] self.rename(path, new_path) model = self.get(path, content=False) self.log.warn(model) return model def increment_filename(self, filename, path='', insert=''): """Increment a filename until it is unique. Parameters ---------- filename : unicode The name of a file, including extension path : unicode The API path of the target's directory Returns ------- name : unicode A filename that is unique, based on the input filename. """ path = path.strip('/') basename, ext = os.path.splitext(filename) for i in itertools.count(): if i: insert_i = '{}{}'.format(insert, i) else: insert_i = '' name = '{basename}{insert}{ext}'.format(basename=basename, insert=insert_i, ext=ext) if not self.exists('{}/{}'.format(path, name)): break return name def validate_notebook_model(self, model): """Add failed-validation message to model""" try: validate(model['content']) except ValidationError as e: model['message'] = 'Notebook Validation failed: {}:\n{}'.format( e.message, json.dumps(e.instance, indent=1, default=lambda obj: '<UNKNOWN>'), ) return model def new_untitled(self, path='', type='', ext=''): """Create a new untitled file or directory in path path must be a directory File extension can be specified. Use `new` to create files with a fully specified path (including filename). """ path = path.strip('/') if not self.dir_exists(path): raise HTTPError(404, 'No such directory: %s' % path) model = {} if type: model['type'] = type if ext == '.ipynb': model.setdefault('type', 'notebook') else: model.setdefault('type', 'file') insert = '' if model['type'] == 'directory': untitled = self.untitled_directory insert = ' ' elif model['type'] == 'notebook': untitled = self.untitled_notebook ext = '.ipynb' elif model['type'] == 'file': untitled = self.untitled_file else: raise HTTPError(400, "Unexpected model type: %r" % model['type']) name = self.increment_filename(untitled + ext, path, insert=insert) path = '{0}/{1}'.format(path, name) return self.new(model, path) def new(self, model=None, path=''): """Create a new file or directory and return its model with no content. To create a new untitled entity in a directory, use `new_untitled`. """ # TODO path = path.strip('/') if model is None: model = {} if path.endswith('.ipynb'): model.setdefault('type', 'notebook') else: model.setdefault('type', 'file') # no content, not a directory, so fill out new-file model if 'content' not in model and model['type'] != 'directory': if model['type'] == 'notebook': model['content'] = new_notebook() model['format'] = 'json' else: model['content'] = '' model['type'] = 'file' model['format'] = 'text' model = self.save(model, path) return model def copy(self, from_path, to_path=None): """Copy an existing file and return its new model. If to_path not specified, it will be the parent directory of from_path. If to_path is a directory, filename will increment `from_path-Copy#.ext`. from_path must be a full path to a file. """ # TODO path = from_path.strip('/') if to_path is not None: to_path = to_path.strip('/') if '/' in path: from_dir, from_name = path.rsplit('/', 1) else: from_dir = '' from_name = path model = self.get(path) model.pop('path', None) model.pop('name', None) if model['type'] == 'directory': raise HTTPError(400, "Can't copy directories") if to_path is None: to_path = from_dir if self.dir_exists(to_path): name = copy_pat.sub('.', from_name) to_name = self.increment_filename(name, to_path, insert='-Copy') to_path = '{0}/{1}'.format(to_path, to_name) model = self.save(model, to_path) return model def log_info(self): self.log.info(self.info_string()) def trust_notebook(self, path): """Explicitly trust a notebook Parameters ---------- path : string The path of a notebook """ model = self.get(path) nb = model['content'] self.log.warn("Trusting notebook %s", path) self.notary.mark_cells(nb, True) self.save(model, path) def check_and_sign(self, nb, path=''): """Check for trusted cells, and sign the notebook. Called as a part of saving notebooks. Parameters ---------- nb : dict The notebook dict path : string The notebook's path (for logging) """ if self.notary.check_cells(nb): self.notary.sign(nb) else: self.log.warn("Saving untrusted notebook %s", path) def mark_trusted_cells(self, nb, saved_by, path=''): """Mark cells as trusted if the notebook signature matches. Called as a part of loading notebooks. Parameters ---------- nb : dict The notebook object (in current nbformat) path : string The notebook's path (for logging) """ if self.user_service.is_trusted_user(saved_by): self.notary.mark_cells(nb, True) else: # commenting out, but leaving behind for a while. trusted = self.notary.check_signature(nb) if not trusted: self.log.warn("Notebook %s is not trusted", path) self.notary.mark_cells(nb, trusted) # self.log.warn("Notebook %s is totally trusted", path) # # all notebooks are trustworthy, because KBase is Pollyanna. def should_list(self, name): """Should this file/directory name be displayed in a listing?""" return not any(fnmatch(name, glob) for glob in self.hide_globs) def info_string(self): return "Workspace Narrative Service with workspace endpoint at %s" % self.kbasews_uri
class Application(SingletonConfigurable): """A singleton application with full configuration support.""" # The name of the application, will usually match the name of the command # line application name = Unicode(u'application') # The description of the application that is printed at the beginning # of the help. description = Unicode(u'This is an application.') # default section descriptions option_description = Unicode(option_description) keyvalue_description = Unicode(keyvalue_description) subcommand_description = Unicode(subcommand_description) python_config_loader_class = PyFileConfigLoader json_config_loader_class = JSONFileConfigLoader # The usage and example string that goes at the end of the help string. examples = Unicode() # A sequence of Configurable subclasses whose config=True attributes will # be exposed at the command line. classes = [] @property def _help_classes(self): """Define `App.help_classes` if CLI classes should differ from config file classes""" return getattr(self, 'help_classes', self.classes) @property def _config_classes(self): """Define `App.config_classes` if config file classes should differ from CLI classes.""" return getattr(self, 'config_classes', self.classes) # The version string of this application. version = Unicode(u'0.0') # the argv used to initialize the application argv = List() # The log level for the application log_level = Enum((0,10,20,30,40,50,'DEBUG','INFO','WARN','ERROR','CRITICAL'), default_value=logging.WARN, config=True, help="Set the log level by value or name.") def _log_level_changed(self, name, old, new): """Adjust the log level when log_level is set.""" if isinstance(new, string_types): new = getattr(logging, new) self.log_level = new self.log.setLevel(new) _log_formatter_cls = LevelFormatter log_datefmt = Unicode("%Y-%m-%d %H:%M:%S", config=True, help="The date format used by logging formatters for %(asctime)s" ) def _log_datefmt_changed(self, name, old, new): self._log_format_changed('log_format', self.log_format, self.log_format) log_format = Unicode("[%(name)s]%(highlevel)s %(message)s", config=True, help="The Logging format template", ) def _log_format_changed(self, name, old, new): """Change the log formatter when log_format is set.""" _log_handler = self.log.handlers[0] _log_formatter = self._log_formatter_cls(fmt=new, datefmt=self.log_datefmt) _log_handler.setFormatter(_log_formatter) log = Instance(logging.Logger) def _log_default(self): """Start logging for this application. The default is to log to stderr using a StreamHandler, if no default handler already exists. The log level starts at logging.WARN, but this can be adjusted by setting the ``log_level`` attribute. """ log = logging.getLogger(self.__class__.__name__) log.setLevel(self.log_level) log.propagate = False _log = log # copied from Logger.hasHandlers() (new in Python 3.2) while _log: if _log.handlers: return log if not _log.propagate: break else: _log = _log.parent if sys.executable.endswith('pythonw.exe'): # this should really go to a file, but file-logging is only # hooked up in parallel applications _log_handler = logging.StreamHandler(open(os.devnull, 'w')) else: _log_handler = logging.StreamHandler() _log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt) _log_handler.setFormatter(_log_formatter) log.addHandler(_log_handler) return log # the alias map for configurables aliases = Dict({'log-level' : 'Application.log_level'}) # flags for loading Configurables or store_const style flags # flags are loaded from this dict by '--key' flags # this must be a dict of two-tuples, the first element being the Config/dict # and the second being the help string for the flag flags = Dict() def _flags_changed(self, name, old, new): """ensure flags dict is valid""" for key,value in iteritems(new): assert len(value) == 2, "Bad flag: %r:%s"%(key,value) assert isinstance(value[0], (dict, Config)), "Bad flag: %r:%s"%(key,value) assert isinstance(value[1], string_types), "Bad flag: %r:%s"%(key,value) # subcommands for launching other applications # if this is not empty, this will be a parent Application # this must be a dict of two-tuples, # the first element being the application class/import string # and the second being the help string for the subcommand subcommands = Dict() # parse_command_line will initialize a subapp, if requested subapp = Instance('traitlets.config.application.Application', allow_none=True) # extra command-line arguments that don't set config values extra_args = List(Unicode) def __init__(self, **kwargs): SingletonConfigurable.__init__(self, **kwargs) # Ensure my class is in self.classes, so my attributes appear in command line # options and config files. if self.__class__ not in self.classes: self.classes.insert(0, self.__class__) def _config_changed(self, name, old, new): SingletonConfigurable._config_changed(self, name, old, new) self.log.debug('Config changed:') self.log.debug(repr(new)) @catch_config_error def initialize(self, argv=None): """Do the basic steps to configure me. Override in subclasses. """ self.parse_command_line(argv) def start(self): """Start the app mainloop. Override in subclasses. """ if self.subapp is not None: return self.subapp.start() def print_alias_help(self): """Print the alias part of the help.""" if not self.aliases: return lines = [] classdict = {} for cls in self._help_classes: # include all parents (up to, but excluding Configurable) in available names for c in cls.mro()[:-3]: classdict[c.__name__] = c for alias, longname in iteritems(self.aliases): classname, traitname = longname.split('.',1) cls = classdict[classname] trait = cls.class_traits(config=True)[traitname] help = cls.class_get_trait_help(trait).splitlines() # reformat first line help[0] = help[0].replace(longname, alias) + ' (%s)'%longname if len(alias) == 1: help[0] = help[0].replace('--%s='%alias, '-%s '%alias) lines.extend(help) # lines.append('') print(os.linesep.join(lines)) def print_flag_help(self): """Print the flag part of the help.""" if not self.flags: return lines = [] for m, (cfg,help) in iteritems(self.flags): prefix = '--' if len(m) > 1 else '-' lines.append(prefix+m) lines.append(indent(dedent(help.strip()))) # lines.append('') print(os.linesep.join(lines)) def print_options(self): if not self.flags and not self.aliases: return lines = ['Options'] lines.append('-'*len(lines[0])) lines.append('') for p in wrap_paragraphs(self.option_description): lines.append(p) lines.append('') print(os.linesep.join(lines)) self.print_flag_help() self.print_alias_help() print() def print_subcommands(self): """Print the subcommand part of the help.""" if not self.subcommands: return lines = ["Subcommands"] lines.append('-'*len(lines[0])) lines.append('') for p in wrap_paragraphs(self.subcommand_description.format( app=self.name)): lines.append(p) lines.append('') for subc, (cls, help) in iteritems(self.subcommands): lines.append(subc) if help: lines.append(indent(dedent(help.strip()))) lines.append('') print(os.linesep.join(lines)) def print_help(self, classes=False): """Print the help for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed. """ self.print_description() self.print_subcommands() self.print_options() if classes: help_classes = self._help_classes if help_classes: print("Class parameters") print("----------------") print() for p in wrap_paragraphs(self.keyvalue_description): print(p) print() for cls in help_classes: cls.class_print_help() print() else: print("To see all available configurables, use `--help-all`") print() self.print_examples() def print_description(self): """Print the application description.""" for p in wrap_paragraphs(self.description): print(p) print() def print_examples(self): """Print usage and examples. This usage string goes at the end of the command line help string and should contain examples of the application's usage. """ if self.examples: print("Examples") print("--------") print() print(indent(dedent(self.examples.strip()))) print() def print_version(self): """Print the version string.""" print(self.version) def update_config(self, config): """Fire the traits events when the config is updated.""" # Save a copy of the current config. newconfig = deepcopy(self.config) # Merge the new config into the current one. newconfig.merge(config) # Save the combined config as self.config, which triggers the traits # events. self.config = newconfig @catch_config_error def initialize_subcommand(self, subc, argv=None): """Initialize a subcommand with argv.""" subapp,help = self.subcommands.get(subc) if isinstance(subapp, string_types): subapp = import_item(subapp) # clear existing instances self.__class__.clear_instance() # instantiate self.subapp = subapp.instance(config=self.config) # and initialize subapp self.subapp.initialize(argv) def flatten_flags(self): """flatten flags and aliases, so cl-args override as expected. This prevents issues such as an alias pointing to InteractiveShell, but a config file setting the same trait in TerminalInteraciveShell getting inappropriate priority over the command-line arg. Only aliases with exactly one descendent in the class list will be promoted. """ # build a tree of classes in our list that inherit from a particular # it will be a dict by parent classname of classes in our list # that are descendents mro_tree = defaultdict(list) for cls in self._help_classes: clsname = cls.__name__ for parent in cls.mro()[1:-3]: # exclude cls itself and Configurable,HasTraits,object mro_tree[parent.__name__].append(clsname) # flatten aliases, which have the form: # { 'alias' : 'Class.trait' } aliases = {} for alias, cls_trait in iteritems(self.aliases): cls,trait = cls_trait.split('.',1) children = mro_tree[cls] if len(children) == 1: # exactly one descendent, promote alias cls = children[0] aliases[alias] = '.'.join([cls,trait]) # flatten flags, which are of the form: # { 'key' : ({'Cls' : {'trait' : value}}, 'help')} flags = {} for key, (flagdict, help) in iteritems(self.flags): newflag = {} for cls, subdict in iteritems(flagdict): children = mro_tree[cls] # exactly one descendent, promote flag section if len(children) == 1: cls = children[0] newflag[cls] = subdict flags[key] = (newflag, help) return flags, aliases @catch_config_error def parse_command_line(self, argv=None): """Parse the command line arguments.""" argv = sys.argv[1:] if argv is None else argv self.argv = [ py3compat.cast_unicode(arg) for arg in argv ] if argv and argv[0] == 'help': # turn `ipython help notebook` into `ipython notebook -h` argv = argv[1:] + ['-h'] if self.subcommands and len(argv) > 0: # we have subcommands, and one may have been specified subc, subargv = argv[0], argv[1:] if re.match(r'^\w(\-?\w)*$', subc) and subc in self.subcommands: # it's a subcommand, and *not* a flag or class parameter return self.initialize_subcommand(subc, subargv) # Arguments after a '--' argument are for the script IPython may be # about to run, not IPython iteslf. For arguments parsed here (help and # version), we want to only search the arguments up to the first # occurrence of '--', which we're calling interpreted_argv. try: interpreted_argv = argv[:argv.index('--')] except ValueError: interpreted_argv = argv if any(x in interpreted_argv for x in ('-h', '--help-all', '--help')): self.print_help('--help-all' in interpreted_argv) self.exit(0) if '--version' in interpreted_argv or '-V' in interpreted_argv: self.print_version() self.exit(0) # flatten flags&aliases, so cl-args get appropriate priority: flags,aliases = self.flatten_flags() loader = KVArgParseConfigLoader(argv=argv, aliases=aliases, flags=flags, log=self.log) config = loader.load_config() self.update_config(config) # store unparsed args in extra_args self.extra_args = loader.extra_args @classmethod def _load_config_files(cls, basefilename, path=None, log=None): """Load config files (py,json) by filename and path. yield each config object in turn. """ if not isinstance(path, list): path = [path] for path in path[::-1]: # path list is in descending priority order, so load files backwards: pyloader = cls.python_config_loader_class(basefilename+'.py', path=path, log=log) jsonloader = cls.json_config_loader_class(basefilename+'.json', path=path, log=log) config = None for loader in [pyloader, jsonloader]: try: config = loader.load_config() except ConfigFileNotFound: pass except Exception: # try to get the full filename, but it will be empty in the # unlikely event that the error raised before filefind finished filename = loader.full_filename or basefilename # problem while running the file if log: log.error("Exception while loading config file %s", filename, exc_info=True) else: if log: log.debug("Loaded config file: %s", loader.full_filename) if config: yield config raise StopIteration @catch_config_error def load_config_file(self, filename, path=None): """Load config files by filename and path.""" filename, ext = os.path.splitext(filename) loaded = [] for config in self._load_config_files(filename, path=path, log=self.log): loaded.append(config) self.update_config(config) if len(loaded) > 1: collisions = loaded[0].collisions(loaded[1]) if collisions: self.log.warn("Collisions detected in {0}.py and {0}.json config files." " {0}.json has higher priority: {1}".format( filename, json.dumps(collisions, indent=2), )) def generate_config_file(self): """generate default config file from Configurables""" lines = ["# Configuration file for %s." % self.name] lines.append('') for cls in self._config_classes: lines.append(cls.class_config_section()) return '\n'.join(lines) def exit(self, exit_status=0): self.log.debug("Exiting application: %s" % self.name) sys.exit(exit_status) @classmethod def launch_instance(cls, argv=None, **kwargs): """Launch a global instance of this Application If a global instance already exists, this reinitializes and starts it """ app = cls.instance(**kwargs) app.initialize(argv) app.start()
class Foo(Configurable): a = Integer(0, help="The integer a.").tag(config=True) b = Unicode('nope').tag(config=True)