New approach working, old approach gone.

Brian E. Granger 10 years ago committed by Jonathan Frederic
parent b208d29d84
commit 7705bfd5ab

@ -291,15 +291,7 @@ class IPythonHandler(AuthenticatedHandler):
#---------------------------------------------------------------
# template rendering
#---------------------------------------------------------------
@property
def nbextensions_tree(self):
return self.settings.get('nbextensions_tree', {})
@property
def nbextensions_notebook(self):
return self.settings.get('nbextensions_notebook', {})
def get_template(self, name):
"""Return the jinja template object for a given name"""
return self.settings['jinja2_env'].get_template(name)

@ -23,17 +23,15 @@ except ImportError:
from urllib import urlretrieve
from jupyter_core.paths import (
jupyter_data_dir, jupyter_path, jupyter_config_dir, SYSTEM_JUPYTER_PATH,
ENV_JUPYTER_PATH, ENV_CONFIG_PATH, SYSTEM_CONFIG_PATH
jupyter_data_dir, jupyter_path, jupyter_config_dir, jupyter_config_path,
SYSTEM_JUPYTER_PATH, ENV_JUPYTER_PATH, ENV_CONFIG_PATH, SYSTEM_CONFIG_PATH
)
from ipython_genutils.path import ensure_dir_exists
from ipython_genutils.py3compat import string_types, cast_unicode_py2, PY3
from ipython_genutils.tempdir import TemporaryDirectory
from ._version import __version__
class ArgumentConflict(ValueError):
pass
from traitlets.config.manager import BaseJSONConfigManager
#------------------------------------------------------------------------------
@ -41,6 +39,10 @@ class ArgumentConflict(ValueError):
#------------------------------------------------------------------------------
class ArgumentConflict(ValueError):
pass
def check_nbextension(files, user=False, sys_prefix=False, prefix=None, nbextensions_dir=None):
"""Check whether nbextension files have been installed
@ -310,8 +312,10 @@ class InstallNBExtensionApp(JupyterApp):
overwrite = Bool(False, config=True, help="Force overwrite of existing files")
symlink = Bool(False, config=True, help="Create symlinks instead of copying files")
user = Bool(False, config=True, help="Whether to do a user install")
sys_prefix = Bool(False, config=True, help="Use the sys.prefix as the prefix")
prefix = Unicode('', config=True, help="Installation prefix")
nbextensions_dir = Unicode('', config=True, help="Full path to nbextensions dir (probably use prefix or user)")
destination = Unicode('', config=True, help="Destination for the copy or symlink")
@ -362,85 +366,135 @@ class InstallNBExtensionApp(JupyterApp):
self.exit(1)
class EnableNBExtensionApp(JupyterApp):
name = "jupyter nbextension enable"
_toggle_flags = {
"debug" : ({
"ToggleNBExtensionApp" : {
"verbose" : 2,
}}, "Extra output"
),
"user" : ({
"ToggleNBExtensionApp" : {
"user" : True,
}}, "Install to the user's Jupyter directory"
),
"sys-prefix" : ({
"ToggleNBExtensionApp" : {
"sys_prefix" : True,
}}, "Use sys.prefix as the prefix for installing nbextensions"
),
"python" : ({
"ToggleNBExtensionApp" : {
"python" : True,
}}, "Install from a Python package"
),
}
class ToggleNBExtensionApp(JupyterApp):
name = "jupyter nbextension enable/disable"
version = __version__
description = "Configure an nbextension to be automatically loaded"
description = "Enable/disable an nbextension using frontend configuration files."
section = Unicode('notebook', config=True,
help=("Which config section to add the extension to. "
"'common' will affect all pages.")
help="""Which config section to add the extension to, 'common' will affect all pages."""
)
aliases = {'section': 'EnableNBExtensionApp.section',
}
aliases = {'section': 'ToggleNBExtensionApp.section'}
flags = _toggle_flags
python = Bool(False, config=True, help="Install from a Python package")
user = Bool(False, config=True, help="Whether to do a user install")
sys_prefix = Bool(False, config=True, help="Use the sys.prefix as the prefix")
_toggle_value = None
def _config_file_name_default(self):
return 'jupyter_notebook_config'
def enable_nbextension(self, name):
# Local import to avoid circular import issue on Py 2
from .services.config import ConfigManager
cm = ConfigManager(parent=self, config=self.config)
cm.update(self.section, {"load_extensions": {name: True}})
def _toggle_nbextension(self, section, require):
print('toggle', section, require)
config_dir = os.path.join(_get_config_dir(user=self.user, sys_prefix=self.sys_prefix), 'nbconfig')
print('config_dir', config_dir)
cm = BaseJSONConfigManager(parent=self, config_dir=config_dir)
if self._toggle_value is None and require not in cm.get(section).get('load_extensions', {}):
sys.exit('{} is not enabled in section {}'.format(require, section))
# We're using a dict as a set - updating with None removes the key
cm.update(section, {"load_extensions": {require: self._toggle_value}})
def toggle_nbextension_python(self, package):
m, nbexts = _get_nbextension_metadata(package)
for nbext in nbexts:
section = nbext['section']
require = nbext['require']
self._toggle_nbextension(section, require)
def toggle_nbextension(self, require):
self._toggle_nbextension(self.section, require)
def start(self):
if not self.extra_args:
sys.exit('No extensions specified')
sys.exit('No extensions or packages specified')
elif len(self.extra_args) > 1:
sys.exit('Please specify one extension at a time')
self.enable_nbextension(self.extra_args[0])
if self.python:
self.toggle_nbextension_python(self.extra_args[0])
else:
self.toggle_nbextension(self.extra_args[0])
class DisableNBExtensionApp(JupyterApp):
name = "jupyter nbextension disable"
version = __version__
description = "Remove the configuration to automatically load an extension"
class EnableNBExtensionApp(ToggleNBExtensionApp):
section = Unicode('notebook', config=True,
help=("Which config section to remove the extension from. "
"This should match the one it was previously added to.")
)
name = "jupyter nbextension enable"
description = "Enable an nbextension using frontend configuration files."
_toggle_value = True
aliases = {'section': 'DisableNBExtensionApp.section',
}
python = Bool(False, config=True, help="Install from a Python package")
def _config_file_name_default(self):
return 'jupyter_notebook_config'
class DisableNBExtensionApp(ToggleNBExtensionApp):
name = "jupyter nbextension disable"
description = "Disable an nbextension using frontend configuration files."
_toggle_value = None
def disable_nbextension(self, name):
# Local import to avoid circular import issue on Py 2
from .services.config import ConfigManager
cm = ConfigManager(parent=self, config=self.config)
if name not in cm.get(self.section).get('load_extensions', {}):
sys.exit('{} is not enabled in section {}'.format(name, self.section))
# We're using a dict as a set - updating with None removes the key
cm.update(self.section, {"load_extensions": {name: None}})
class ListNBExtensionsApp(JupyterApp):
name = "jupyter nbextension list"
version = __version__
description = "List all nbextensions known by the configuration system"
def list_nbextensions(self):
config_dirs = [os.path.join(p, 'nbconfig') for p in jupyter_config_path()]
for config_dir in config_dirs:
print('config dir: {}'.format(config_dir))
cm = BaseJSONConfigManager(parent=self, config_dir=config_dir)
for section in ['notebook', 'tree']:
data = cm.get(section)
if 'load_extensions' in data:
print(' section: {}'.format(section))
print(' {}'.format(data))
def start(self):
if not self.extra_args:
sys.exit('No extensions specified')
elif len(self.extra_args) > 1:
sys.exit('Please specify one extension at a time')
self.list_nbextensions()
self.disable_nbextension(self.extra_args[0])
_examples = """
jupyter nbextension list # list all configured nbextensions
jupyter nbextension install --python <packagename> # install an nbextension from a Python package
jupyter nbextension enable --python <packagename> # enable all nbextensions in a Python package
jupyter nbextension disable --python <packagename> # disable all nbextensions in a Python package
"""
class NBExtensionApp(JupyterApp):
name = "jupyter nbextension"
version = __version__
description = "Work with Jupyter notebook extensions"
examples = _examples
subcommands = dict(
install=(InstallNBExtensionApp,
"""Install notebook extensions"""
),
enable=(EnableNBExtensionApp, "Enable a notebook extension"),
disable=(DisableNBExtensionApp, "Disable a notebook extension"),
install=(InstallNBExtensionApp,"Install an nbextension"),
enable=(EnableNBExtensionApp, "Enable an nbextension"),
disable=(DisableNBExtensionApp, "Disable an nbextension"),
list=(ListNBExtensionsApp, "List nbextensions")
)
def start(self):

@ -4,7 +4,6 @@
# Distributed under the terms of the Modified BSD License.
import os
import json
from tornado import web
HTTPError = web.HTTPError
@ -22,7 +21,6 @@ class NotebookHandler(IPythonHandler):
redirects to the '/files/' handler if the name is not given."""
path = path.strip('/')
cm = self.contents_manager
nbextensions = json.dumps(self.nbextensions_notebook)
# will raise 404 on not found
try:
@ -42,7 +40,6 @@ class NotebookHandler(IPythonHandler):
notebook_name=name,
kill_kernel=False,
mathjax_url=self.mathjax_url,
nbextensions=nbextensions
)
)

@ -695,12 +695,6 @@ class NotebookApp(JupyterApp):
path.append(os.path.join(get_ipython_dir(), 'nbextensions'))
return path
nbextensions_tree = Dict(config=True,
help="A list of nbextensions to enable for the tree/dashboard page.")
nbextensions_notebook = Dict(config=True,
help="A list of nbextensions to enable for the notebook page.")
websocket_url = Unicode("", config=True,
help="""The base URL for websockets,
if it differs from the HTTP server (hint: it almost certainly doesn't).

@ -5,13 +5,46 @@
import os.path
from traitlets.config.manager import BaseJSONConfigManager
from jupyter_core.paths import jupyter_config_dir
from traitlets import Unicode
from traitlets.config.manager import BaseJSONConfigManager, recursive_update
from jupyter_core.paths import jupyter_config_dir, jupyter_config_path
from traitlets import Unicode, Instance, List
from traitlets.config import LoggingConfigurable
class ConfigManager(BaseJSONConfigManager):
class ConfigManager(LoggingConfigurable):
"""Config Manager used for storing notebook frontend config"""
config_dir = Unicode(config=True)
def _config_dir_default(self):
# Public API
def get(self, section_name):
"""Get the config from all config sections."""
config = {}
for p in self.read_config_path:
cm = BaseJSONConfigManager(config_dir=p)
recursive_update(config, cm.get(section_name))
return config
def set(self, section_name, data):
"""Set the config only to the user's config."""
self._write_config_manager.set(section_name, data)
def update(self, section_name, new_data):
"""Update the config only to the user's config."""
self._write_config_manager.update(section_name, new_data)
# Private API
read_config_path = List(Unicode())
def _read_config_path_default(self):
return [os.path.join(p, 'nbconfig') for p in jupyter_config_path()]
write_config_dir = Unicode()
def _write_config_dir_default(self):
return os.path.join(jupyter_config_dir(), 'nbconfig')
write_config_manager = Instance(BaseJSONConfigManager)
def _write_config_manager_default(self):
return BaseJSONConfigManager(config_dir=self.write_config_dir)
def _write_config_dir_changed(self, name, old, new):
self.write_config_manager = BaseJSONConfigManager(config_dir=self.write_config_dir)

@ -855,6 +855,7 @@ define([
}
var utils = {
extensions_loaded: extensions_loaded,
load_extension: load_extension,
load_extensions: load_extensions,
filter_extensions: filter_extensions,

@ -79,8 +79,6 @@ require([
config_section.load();
var common_config = new configmod.ConfigSection('common', common_options);
common_config.load();
var nbextensions = $('body').data('nbextensions');
// Instantiate the main objects
@ -188,8 +186,6 @@ require([
});
// Now actually load nbextensions
var active = utils.filter_extensions(nbextensions);
utils.load_extensions.apply(null, active);
utils.load_extensions_from_config(config_section);
utils.load_extensions_from_config(common_config);
notebook.load_notebook(common_options.notebook_path);

@ -44,8 +44,6 @@ require([
var common_config = new config.ConfigSection('common', common_options);
common_config.load();
var nbextensions = $('body').data('nbextensions');
// Instantiate the main objects
page = new page.Page();
@ -148,8 +146,6 @@ require([
events.trigger('app_initialized.DashboardApp');
// Now actually load nbextensions
var active = utils.filter_extensions(nbextensions);
utils.load_extensions.apply(null, active);
utils.load_extensions_from_config(cfg);
utils.load_extensions_from_config(common_config);

@ -30,7 +30,6 @@ data-base-url="{{base_url | urlencode}}"
data-ws-url="{{ws_url | urlencode}}"
data-notebook-name="{{notebook_name | urlencode}}"
data-notebook-path="{{notebook_path | urlencode}}"
data-nbextensions="{{nbextensions}}"
{% endblock %}

@ -8,7 +8,6 @@
data-base-url="{{base_url | urlencode}}"
data-notebook-path="{{notebook_path | urlencode}}"
data-terminals-available="{{terminals_available}}"
data-nbextensions="{{nbextensions}}"
{% endblock %}

@ -3,7 +3,6 @@
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
from tornado import web
from ..base.handlers import IPythonHandler, path_regex
from ..utils import url_path_join, url_escape
@ -38,7 +37,6 @@ class TreeHandler(IPythonHandler):
def get(self, path=''):
path = path.strip('/')
cm = self.contents_manager
nbextensions = json.dumps(self.nbextensions_tree)
if cm.dir_exists(path=path):
if cm.is_hidden(path):
@ -51,7 +49,6 @@ class TreeHandler(IPythonHandler):
notebook_path=path,
breadcrumbs=breadcrumbs,
terminals_available=self.settings['terminals_available'],
nbextensions=nbextensions
))
elif cm.file_exists(path):
# it's not a directory, we have redirecting to do

Loading…
Cancel
Save