def list_nbextensions(self): """List all the nbextensions""" config_dirs = [os.path.join(p, 'nbconfig') for p in jupyter_config_path()] print("Known bundlerextensions:") for config_dir in config_dirs: head = u' config dir: {}'.format(config_dir) head_shown = False cm = BaseJSONConfigManager(parent=self, config_dir=config_dir) data = cm.get('notebook') if 'bundlerextensions' in data: if not head_shown: # only show heading if there is an nbextension here print(head) head_shown = True for bundler_id, info in data['bundlerextensions'].items(): label = info.get('label') module = info.get('module_name') if label is None or module is None: msg = u' {} {}'.format(bundler_id, RED_DISABLED) else: msg = u' "{}" from {} {}'.format( label, module, GREEN_ENABLED ) print(msg)
def test_json(): tmpdir = tempfile.mkdtemp() try: with open(os.path.join(tmpdir, 'foo.json'), 'w') as f: json.dump(dict(a=1), f) # also make a foo.d/ directory with multiple json files os.makedirs(os.path.join(tmpdir, 'foo.d')) with open(os.path.join(tmpdir, 'foo.d', 'a.json'), 'w') as f: json.dump(dict(a=2, b=1), f) with open(os.path.join(tmpdir, 'foo.d', 'b.json'), 'w') as f: json.dump(dict(a=3, b=2, c=3), f) manager = BaseJSONConfigManager(config_dir=tmpdir, read_directory=False) data = manager.get('foo') assert 'a' in data assert 'b' not in data assert 'c' not in data assert data['a'] == 1 manager = BaseJSONConfigManager(config_dir=tmpdir, read_directory=True) data = manager.get('foo') assert 'a' in data assert 'b' in data assert 'c' in data # files should be read in order foo.d/a.json foo.d/b.json foo.json assert data['a'] == 1 assert data['b'] == 2 assert data['c'] == 3 finally: shutil.rmtree(tmpdir)
def list_nbextensions(self): """List all the nbextensions""" config_dirs = [os.path.join(p, 'nbconfig') for p in jupyter_config_path()] print("Known bundlerextensions:") for config_dir in config_dirs: head = u' config dir: {}'.format(config_dir) head_shown = False cm = BaseJSONConfigManager(parent=self, config_dir=config_dir) data = cm.get('notebook') if 'bundlerextensions' in data: if not head_shown: # only show heading if there is an nbextension here print(head) head_shown = True for bundler_id, info in data['bundlerextensions'].items(): label = info.get('label') module = info.get('module_name') if label is None or module is None: msg = u' {} {}'.format(bundler_id, RED_DISABLED) else: msg = u' "{}" from {} {}'.format( label, module, GREEN_ENABLED ) print(msg)
def test_check_disable(): test_check_enable() disable_nbextension(section='notebook', require='notebook_magiclight/index') config_dir = os.path.join(_get_config_dir(user=True), 'nbconfig') cm = BaseJSONConfigManager(config_dir=config_dir) enabled = cm.get('notebook').get('load_extensions', {}).get(u'ƒ', False) assert not enabled
def test_nbextension_disable(self): self.test_nbextension_enable() disable_nbextension(section='notebook', require=u'ƒ') config_dir = os.path.join(_get_config_dir(user=True), 'nbconfig') cm = BaseJSONConfigManager(config_dir=config_dir) enabled = cm.get('notebook').get('load_extensions', {}).get(u'ƒ', False) assert not enabled
def get(self, section_name): """Get the config from all config sections.""" config = {} # step through back to front, to ensure front of the list is top priority for p in self.read_config_path[::-1]: cm = BaseJSONConfigManager(config_dir=p) recursive_update(config, cm.get(section_name)) return config
def get(self, section_name): """Get the config from all config sections.""" config = {} # step through back to front, to ensure front of the list is top priority for p in self.read_config_path[::-1]: cm = BaseJSONConfigManager(config_dir=p) recursive_update(config, cm.get(section_name)) return config
def test_disable(self): """Should remove the bundler from the notebook configuration.""" self.test_enable() disable_bundler_python('notebook.bundler.zip_bundler') config_dir = os.path.join(_get_config_dir(user=True), 'nbconfig') cm = BaseJSONConfigManager(config_dir=config_dir) bundlers = cm.get('notebook').get('bundlerextensions', {}) self.assertEqual(len(bundlers), 0)
def test_enable(self): """Should add the bundler to the notebook configuration.""" enable_bundler_python('notebook.bundler.zip_bundler') config_dir = os.path.join(_get_config_dir(user=True), 'nbconfig') cm = BaseJSONConfigManager(config_dir=config_dir) bundlers = cm.get('notebook').get('bundlerextensions', {}) self.assertEqual(len(bundlers), 1) self.assertIn('notebook_zip_download', bundlers)
def test_enable(self): """Should add the bundler to the notebook configuration.""" enable_bundler_python('notebook.bundler.zip_bundler') config_dir = os.path.join(_get_config_dir(user=True), 'nbconfig') cm = BaseJSONConfigManager(config_dir=config_dir) bundlers = cm.get('notebook').get('bundlerextensions', {}) self.assertEqual(len(bundlers), 1) self.assertIn('notebook_zip_download', bundlers)
def test_nbextensionpy_enable(self): self._inject_mock_extension('notebook') install_nbextension_python('mockextension', user=True) enable_nbextension_python('mockextension') config_dir = os.path.join(_get_config_dir(user=True), 'nbconfig') cm = BaseJSONConfigManager(config_dir=config_dir) enabled = cm.get('notebook').get('load_extensions', {}).get('_mockdestination/index', False) assert enabled
def test_disable(self): """Should remove the bundler from the notebook configuration.""" self.test_enable() disable_bundler_python('notebook.bundler.zip_bundler') config_dir = os.path.join(_get_config_dir(user=True), 'nbconfig') cm = BaseJSONConfigManager(config_dir=config_dir) bundlers = cm.get('notebook').get('bundlerextensions', {}) self.assertEqual(len(bundlers), 0)
def test_nbextension_disable(self): self.test_nbextension_enable() disable_nbextension(section='notebook', require=u'ƒ') config_dir = os.path.join(_get_config_dir(user=True), 'nbconfig') cm = BaseJSONConfigManager(config_dir=config_dir) enabled = cm.get('notebook').get('load_extensions', {}).get(u'ƒ', False) assert not enabled
def find_nbgallery_url(): for config_dir in [os.path.join(p, 'nbconfig') for p in jupyter_config_path()]: cm = BaseJSONConfigManager(config_dir=config_dir) config = cm.get('common') try: return config['nbgallery']['url'] except: # keep going pass # Return from environment, or else nbgallery rails default return os.getenv('NBGALLERY_URL', 'http://localhost:3000')
def test_nbextensionpy_enable(self): self._inject_mock_extension('notebook') install_nbextension_python('mockextension', user=True) enable_nbextension_python('mockextension') config_dir = os.path.join(_get_config_dir(user=True), 'nbconfig') cm = BaseJSONConfigManager(config_dir=config_dir) enabled = cm.get('notebook').get('load_extensions', {}).get('_mockdestination/index', False) assert enabled
def test_nbextension_enable(self): with TemporaryDirectory() as d: f = u'ƒ.js' src = pjoin(d, f) touch(src) install_nbextension(src, user=True) enable_nbextension(section='notebook', require=u'ƒ') config_dir = os.path.join(_get_config_dir(user=True), 'nbconfig') cm = BaseJSONConfigManager(config_dir=config_dir) enabled = cm.get('notebook').get('load_extensions', {}).get(u'ƒ', False) assert enabled
def test_nbextension_enable(self): with TemporaryDirectory() as d: f = u'ƒ.js' src = pjoin(d, f) touch(src) install_nbextension(src, user=True) enable_nbextension(section='notebook', require=u'ƒ') config_dir = os.path.join(_get_config_dir(user=True), 'nbconfig') cm = BaseJSONConfigManager(config_dir=config_dir) enabled = cm.get('notebook').get('load_extensions', {}).get(u'ƒ', False) assert enabled
def _set_bundler_state(name, label, module_name, group, state, user=True, sys_prefix=False, logger=None): """Set whether a bundler is enabled or disabled. Returns True if the final state is the one requested. Parameters ---------- name : string Unique name of the bundler label : string Human-readable label for the bundler menu item in the notebook UI module_name : string Dotted module/package name containing the bundler group : string 'download' or 'deploy' indicating the parent menu containing the label state : bool The state in which to leave the extension user : bool [default: True] Whether to update the user's .jupyter/nbconfig directory sys_prefix : bool [default: False] Whether to update the sys.prefix, i.e. environment. Will override `user`. logger : Jupyter logger [optional] Logger instance to use """ user = False if sys_prefix else user config_dir = os.path.join( _get_config_dir(user=user, sys_prefix=sys_prefix), 'nbconfig') cm = BaseJSONConfigManager(config_dir=config_dir) if logger: logger.info("{} {} bundler {}...".format( "Enabling" if state else "Disabling", name, module_name )) if state: cm.update(BUNDLER_SECTION, { BUNDLER_SUBSECTION: { name: { "label": label, "module_name": module_name, "group" : group } } }) else: cm.update(BUNDLER_SECTION, { BUNDLER_SUBSECTION: { name: None } }) return (cm.get(BUNDLER_SECTION) .get(BUNDLER_SUBSECTION, {}) .get(name) is not None) == state
def set_password(args): password = args.password while not password : password1 = getpass("" if args.quiet else "Provide password: "******"" if args.quiet else "Repeat password: "******"Passwords do not match, try again") elif len(password1) < 4: print("Please provide at least 4 characters") else: password = password1 password_hash = passwd(password) cfg = BaseJSONConfigManager(config_dir=jupyter_config_dir()) cfg.update('jupyter_notebook_config', { 'NotebookApp': { 'password': password_hash, } }) if not args.quiet: print("password stored in config dir: %s" % jupyter_config_dir())
def test_json(): tmpdir = tempfile.mkdtemp() try: with open(os.path.join(tmpdir, 'foo.json'), 'w') as f: json.dump(dict(a=1), f) # also make a foo.d/ directory with multiple json files os.makedirs(os.path.join(tmpdir, 'foo.d')) with open(os.path.join(tmpdir, 'foo.d', 'a.json'), 'w') as f: json.dump(dict(a=2, b=1), f) with open(os.path.join(tmpdir, 'foo.d', 'b.json'), 'w') as f: json.dump(dict(a=3, b=2, c=3), f) manager = BaseJSONConfigManager(config_dir=tmpdir, read_directory=False) data = manager.get('foo') assert 'a' in data assert 'b' not in data assert 'c' not in data assert data['a'] == 1 manager = BaseJSONConfigManager(config_dir=tmpdir, read_directory=True) data = manager.get('foo') assert 'a' in data assert 'b' in data assert 'c' in data # files should be read in order foo.d/a.json foo.d/b.json foo.json assert data['a'] == 1 assert data['b'] == 2 assert data['c'] == 3 finally: shutil.rmtree(tmpdir)
def _set_bundler_state(name, label, module_name, group, state, user=True, sys_prefix=False, logger=None): """Set whether a bundler is enabled or disabled. Returns True if the final state is the one requested. Parameters ---------- name : string Unique name of the bundler label : string Human-readable label for the bundler menu item in the notebook UI module_name : string Dotted module/package name containing the bundler group : string 'download' or 'deploy' indicating the parent menu containing the label state : bool The state in which to leave the extension user : bool [default: True] Whether to update the user's .jupyter/nbconfig directory sys_prefix : bool [default: False] Whether to update the sys.prefix, i.e. environment. Will override `user`. logger : Jupyter logger [optional] Logger instance to use """ user = False if sys_prefix else user config_dir = os.path.join( _get_config_dir(user=user, sys_prefix=sys_prefix), 'nbconfig') cm = BaseJSONConfigManager(config_dir=config_dir) if logger: logger.info("{} {} bundler {}...".format( "Enabling" if state else "Disabling", name, module_name )) if state: cm.update(BUNDLER_SECTION, { BUNDLER_SUBSECTION: { name: { "label": label, "module_name": module_name, "group" : group } } }) else: cm.update(BUNDLER_SECTION, { BUNDLER_SUBSECTION: { name: None } }) return (cm.get(BUNDLER_SECTION) .get(BUNDLER_SUBSECTION, {}) .get(name) is not None) == state
def _update_write_config_dir(self, change): self.write_config_manager = BaseJSONConfigManager( config_dir=self.write_config_dir)
def _get_config(self, user=True): cm = BaseJSONConfigManager(config_dir=_get_config_dir(user)) data = cm.get("jupyter_notebook_config") return data.get("NotebookApp", {}).get("nbserver_extensions", {})
def test_json(): tmpdir = tempfile.mkdtemp() try: root_data = dict(a=1, x=2, nest={'a': 1, 'x': 2}) with open(os.path.join(tmpdir, 'foo.json'), 'w') as f: json.dump(root_data, f) # also make a foo.d/ directory with multiple json files os.makedirs(os.path.join(tmpdir, 'foo.d')) with open(os.path.join(tmpdir, 'foo.d', 'a.json'), 'w') as f: json.dump(dict(a=2, b=1, nest={'a': 2, 'b': 1}), f) with open(os.path.join(tmpdir, 'foo.d', 'b.json'), 'w') as f: json.dump( dict(a=3, b=2, c=3, nest={ 'a': 3, 'b': 2, 'c': 3 }, only_in_b={'x': 1}), f) manager = BaseJSONConfigManager(config_dir=tmpdir, read_directory=False) data = manager.get('foo') assert 'a' in data assert 'x' in data assert 'b' not in data assert 'c' not in data assert data['a'] == 1 assert 'x' in data['nest'] # if we write it out, it also shouldn't pick up the subdirectoy manager.set('foo', data) data = manager.get('foo') assert data == root_data manager = BaseJSONConfigManager(config_dir=tmpdir, read_directory=True) data = manager.get('foo') assert 'a' in data assert 'b' in data assert 'c' in data # files should be read in order foo.d/a.json foo.d/b.json foo.json assert data['a'] == 1 assert data['b'] == 2 assert data['c'] == 3 assert data['nest']['a'] == 1 assert data['nest']['b'] == 2 assert data['nest']['c'] == 3 assert data['nest']['x'] == 2 # when writing out, we don't want foo.d/*.json data to be included in the root foo.json manager.set('foo', data) manager = BaseJSONConfigManager(config_dir=tmpdir, read_directory=False) data = manager.get('foo') assert data == root_data finally: shutil.rmtree(tmpdir)
import os import sys from nbconvert import nbconvertapp from notebook.config_manager import BaseJSONConfigManager from jupyter_core.paths import jupyter_config_path # Check if bundler extension is enabled bundler_enabled = False config_dirs = [os.path.join(p, 'nbconfig') for p in jupyter_config_path()] for config_dir in config_dirs: cm = BaseJSONConfigManager(config_dir=config_dir) data = cm.get('notebook') if 'bundlerextensions' in data: for bundler_id, info in data['bundlerextensions'].items(): label = info.get('label') module = info.get('module_name') if module == 'jupyter_docx_bundler': bundler_enabled = True if not bundler_enabled: sys.exit('jupyter-dox-bundler not enabled.') # Check if nbconvert lists docx as available format formats = nbconvertapp.get_export_names() if 'docx' not in formats: sys.exit('*.docx not in nbconvert export-names.')
def _default_write_config_manager(self): return BaseJSONConfigManager(config_dir=self.write_config_dir)
def test_json(): tmpdir = tempfile.mkdtemp() try: root_data = dict(a=1, x=2, nest={'a':1, 'x':2}) with open(os.path.join(tmpdir, 'foo.json'), 'w') as f: json.dump(root_data, f) # also make a foo.d/ directory with multiple json files os.makedirs(os.path.join(tmpdir, 'foo.d')) with open(os.path.join(tmpdir, 'foo.d', 'a.json'), 'w') as f: json.dump(dict(a=2, b=1, nest={'a':2, 'b':1}), f) with open(os.path.join(tmpdir, 'foo.d', 'b.json'), 'w') as f: json.dump(dict(a=3, b=2, c=3, nest={'a':3, 'b':2, 'c':3}, only_in_b={'x':1}), f) manager = BaseJSONConfigManager(config_dir=tmpdir, read_directory=False) data = manager.get('foo') assert 'a' in data assert 'x' in data assert 'b' not in data assert 'c' not in data assert data['a'] == 1 assert 'x' in data['nest'] # if we write it out, it also shouldn't pick up the subdirectoy manager.set('foo', data) data = manager.get('foo') assert data == root_data manager = BaseJSONConfigManager(config_dir=tmpdir, read_directory=True) data = manager.get('foo') assert 'a' in data assert 'b' in data assert 'c' in data # files should be read in order foo.d/a.json foo.d/b.json foo.json assert data['a'] == 1 assert data['b'] == 2 assert data['c'] == 3 assert data['nest']['a'] == 1 assert data['nest']['b'] == 2 assert data['nest']['c'] == 3 assert data['nest']['x'] == 2 # when writing out, we don't want foo.d/*.json data to be included in the root foo.json manager.set('foo', data) manager = BaseJSONConfigManager(config_dir=tmpdir, read_directory=False) data = manager.get('foo') assert data == root_data finally: shutil.rmtree(tmpdir)
def _get_config(self, user=True): cm = BaseJSONConfigManager(config_dir=_get_config_dir(user)) data = cm.get("jupyter_notebook_config") return data.get("NotebookApp", {}).get("nbserver_extensions", {})