Exemple #1
0
 def test_v2raise(self):
     fd, fname = mkstemp('.json', prefix=u'μnïcø∂e')
     f = os.fdopen(fd, 'w')
     f.write(json2file)
     f.close()
     # Unlink the file
     cl = JSONFileConfigLoader(fname, log=log)
     with self.assertRaises(ValueError):
         cl.load_config()
Exemple #2
0
 def test_v2raise(self):
     fd, fname = mkstemp('.json', prefix=u'μnïcø∂e')
     f = os.fdopen(fd, 'w')
     f.write(json2file)
     f.close()
     # Unlink the file
     cl = JSONFileConfigLoader(fname, log=log)
     with self.assertRaises(ValueError):
         cl.load_config()
def persist_config(mode=0o600):
    """Context manager that can be use to modify a config object

    On exit of the context manager, the config will be written back to disk, 
    by default with 600 permissions.
    """

    loader = JSONFileConfigLoader('jupyter_notebook_config.json',
                                  jupyter_config_dir())
    try:
        config = loader.load_config()
    except ConfigFileNotFound:
        config = Config()

    yield config

    filepath = os.path.join(jupyter_config_dir(),
                            'jupyter_notebook_config.json')
    with io.open(filepath, 'w') as f:
        f.write(six.u(json.dumps(config, indent=2)))
    try:
        os.chmod(filepath, mode)
    except Exception:
        traceback.print_exc()

        print("Something went wrong changing file permissions")
Exemple #4
0
 def test_json(self):
     fd, fname = mkstemp('.json', prefix=u'μnïcø∂e')
     f = os.fdopen(fd, 'w')
     f.write(json1file)
     f.close()
     # Unlink the file
     cl = JSONFileConfigLoader(fname, log=log)
     config = cl.load_config()
     self._check_conf(config)
Exemple #5
0
 def test_json(self):
     fd, fname = mkstemp(".json")
     f = os.fdopen(fd, "w")
     f.write(json1file)
     f.close()
     # Unlink the file
     cl = JSONFileConfigLoader(fname, log=log)
     config = cl.load_config()
     self._check_conf(config)
Exemple #6
0
 def test_json(self):
     fd, fname = mkstemp('.json', prefix=u'μnïcø∂e')
     f = os.fdopen(fd, 'w')
     f.write(json1file)
     f.close()
     # Unlink the file
     cl = JSONFileConfigLoader(fname, log=log)
     config = cl.load_config()
     self._check_conf(config)
    def load(self):
        ## Load the key
        keypath = self.__credential_path.parent / "useless_or_not"
        with open(keypath) as fid:
            token = fid.read()

        self.__crypto = cfe.Fernet(token.encode())
        loader = JSONFileConfigLoader(
            self.__credential_path.name,
            str(self.__credential_path.parent.resolve()))
        self.__config = loader.load_config()
Exemple #8
0
def load_json_config(json_filename):
    """ Load config as JSON file
    :param json_filename: Filename of JSON file
    :return: Traitlets based configuration
    """
    json_config = os.path.join(jupyter_config_dir(), json_filename)
    if debug is True: print("Configuring %s" % json_config)
    if os.path.isfile(json_config) is True:
        cl = JSONFileConfigLoader(json_config)
        config = cl.load_config()
    else:
        config = Config()
    return config
    def enable_server_extension(self, extension):
        loader = JSONFileConfigLoader('jupyter_notebook_config.json', jupyter_config_dir())
        try:
            config = loader.load_config()
        except ConfigFileNotFound:
            config = Config()

        if 'server_extensions' not in config.NotebookApp:
            config.NotebookApp.server_extensions = []
        if extension not in config.NotebookApp.server_extensions:
            config.NotebookApp.server_extensions.append(extension)

        # save the updated config
        with io.open(os.path.join(jupyter_config_dir(), 'jupyter_notebook_config.json'), 'w+') as f:
            f.write(six.u(json.dumps(config, indent=2)))
Exemple #10
0
    def test_json_context_bad_write(self):
        fd, fname = mkstemp('.json', prefix=u'μnïcø∂e')
        f = os.fdopen(fd, 'w')
        f.write('{}')
        f.close()

        with JSONFileConfigLoader(fname, log=log) as config:
            config.A.b = 1

        with self.assertRaises(TypeError):
            with JSONFileConfigLoader(fname, log=log) as config:
                config.A.cant_json = lambda x: x

        loader = JSONFileConfigLoader(fname, log=log)
        cfg = loader.load_config()
        assert cfg.A.b == 1
        assert 'cant_json' not in cfg.A
Exemple #11
0
    def test_json_context_bad_write(self):
        fd, fname = mkstemp('.json', prefix=u'μnïcø∂e')
        f = os.fdopen(fd, 'w')
        f.write('{}')
        f.close()

        with JSONFileConfigLoader(fname, log=log) as config:
            config.A.b = 1

        with self.assertRaises(TypeError):
            with JSONFileConfigLoader(fname, log=log) as config:
                config.A.cant_json = lambda x: x

        loader = JSONFileConfigLoader(fname, log=log)
        cfg = loader.load_config()
        assert cfg.A.b == 1
        assert 'cant_json' not in cfg.A
Exemple #12
0
    def test_json_context_bad_write(self):
        fd, fname = mkstemp(".json")
        f = os.fdopen(fd, "w")
        f.write("{}")
        f.close()

        with JSONFileConfigLoader(fname, log=log) as config:
            config.A.b = 1

        with self.assertRaises(TypeError):
            with JSONFileConfigLoader(fname, log=log) as config:
                config.A.cant_json = lambda x: x

        loader = JSONFileConfigLoader(fname, log=log)
        cfg = loader.load_config()
        assert cfg.A.b == 1
        assert "cant_json" not in cfg.A
Exemple #13
0
    def test_json_context_bad_write(self):
        fd, fname = mkstemp(".json", prefix="μnïcø∂e")
        f = os.fdopen(fd, "w")
        f.write("{}")
        f.close()

        with JSONFileConfigLoader(fname, log=log) as config:
            config.A.b = 1

        with self.assertRaises(TypeError):
            with JSONFileConfigLoader(fname, log=log) as config:
                config.A.cant_json = lambda x: x

        loader = JSONFileConfigLoader(fname, log=log)
        cfg = loader.load_config()
        assert cfg.A.b == 1
        assert "cant_json" not in cfg.A
    def enable_server_extension(self, extension):
        loader = JSONFileConfigLoader('jupyter_notebook_config.json',
                                      jupyter_config_dir())
        try:
            config = loader.load_config()
        except ConfigFileNotFound:
            config = Config()

        if 'server_extensions' not in config.NotebookApp:
            config.NotebookApp.server_extensions = []
        if extension not in config.NotebookApp.server_extensions:
            config.NotebookApp.server_extensions.append(extension)

        # save the updated config
        with io.open(
                os.path.join(jupyter_config_dir(),
                             'jupyter_notebook_config.json'), 'w+') as f:
            f.write(six.u(json.dumps(config, indent=2)))
Exemple #15
0
def _load_config_files(basefilename, path=None):
    """Load config files (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:
        loader = JSONFileConfigLoader(basefilename+'.json', path=path)
        config = None
        try:
            config = loader.load_config()
        except ConfigFileNotFound:
            pass
        if config:
            yield config
Exemple #16
0
def _load_config_files(basefilename, path=None):
    """Load config files (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:
        loader = JSONFileConfigLoader(basefilename + '.json', path=path)
        config = None
        try:
            config = loader.load_config()
        except ConfigFileNotFound:
            pass
        if config:
            yield config
Exemple #17
0
def persist_config(mode=0o600):
    """Context manager that can be use to modify a config object

    On exit of the context manager, the config will be written back to disk, 
    by default with 600 permissions.
    """

    loader = JSONFileConfigLoader('jupyter_notebook_config.json', jupyter_config_dir())
    try:
        config = loader.load_config()
    except ConfigFileNotFound:
        config = Config()

    yield config

    filepath = os.path.join(jupyter_config_dir(), 'jupyter_notebook_config.json')
    with io.open(filepath, 'w') as f:
        f.write(six.u(json.dumps(config, indent=2)))
    try:
        os.chmod(filepath, mode)
    except Exception:
        traceback.print_exc()

        print("Something went wrong changing file permissions")
Exemple #18
0
 def load(self):
     loader = JSONFileConfigLoader(self.__config_path.name,
                                   str(self.__config_path.parent.resolve()))
     self.__config = loader.load_config()
        with io.open(join(cert_dir, certfile), "wt") as f:
            f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode("utf8"))
        with io.open(join(cert_dir, keyfile), "wt") as f:
            f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode("utf8"))


if __name__ == "__main__":
    print("This guide you into securing your notebook server")
    print("first choose a password.")
    pw = passwd()
    print("We will store your password encrypted in the notebook configuration file: ")
    print(pw)

    loader = JSONFileConfigLoader("jupyter_notebook_config.json", jupyter_config_dir())
    try:
        config = loader.load_config()
    except ConfigFileNotFound:
        config = Config()

    config.NotebookApp.password = pw

    with io.open(os.path.join(jupyter_config_dir(), "jupyter_notebook_config.json"), "w") as f:
        f.write(six.u(json.dumps(config, indent=2)))

    print("... done")
    print()

    print("Now let's generate self-signed certificates to secure your connexion.")
    print("where should the certificate live?")
    location = input("path [~/.ssh]: ")
    if not location.strip():
Exemple #20
0
                crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode('utf8'))


if __name__ == '__main__':
    print("This guide you into securing your notebook server")
    print("first choose a password.")
    pw = passwd()
    print(
        "We will store your password encrypted in the notebook configuration file: "
    )
    print(pw)

    loader = JSONFileConfigLoader('jupyter_notebook_config.json',
                                  jupyter_config_dir())
    try:
        config = loader.load_config()
    except ConfigFileNotFound:
        config = Config()

    config.NotebookApp.password = pw

    with io.open(
            os.path.join(jupyter_config_dir(), 'jupyter_notebook_config.json'),
            'w') as f:
        f.write(six.u(json.dumps(config, indent=2)))

    print('... done')
    print()

    print(
        "Now let's generate self-signed certificates to secure your connexion."
# Install nbextensions
src = 'nbextensions'
destination = os.path.join(data_dir, 'nbextensions')
print("Install notebook extensions to %s" % destination)
recursive_overwrite(src, destination)


#
# 3. Update nbconvert configuration
#
json_config = os.path.join(jupyter_config_dir(), 'jupyter_nbconvert_config.json')
print("Configuring %s" % json_config)
if os.path.isfile(json_config) is True:
    cl = JSONFileConfigLoader(json_config)
    config = cl.load_config()
else:
    config = Config()
newconfig = Config()
# Set template path, pre- and postprocessors of notebook extensions
newconfig.Exporter.template_path = [os.path.join(data_dir, 'templates')]
newconfig.Exporter.preprocessors = ["pre_codefolding.CodeFoldingPreprocessor", "pre_pymarkdown.PyMarkdownPreprocessor"]
newconfig.NbConvertApp.postprocessor_class = 'post_embedhtml.EmbedPostProcessor'
config.merge(newconfig)
config.version = 1
s=json.dumps(config, indent=2, separators=(',', ': '), sort_keys=True)
with open(json_config, 'w') as f:
    f.write(s)

py_config = os.path.join(jupyter_config_dir(), 'jupyter_nbconvert_config.py')
print("Configuring %s" % py_config)
# now test if path exists
if os.path.exists(config_dir) is False:
    os.mkdir(config_dir)
if os.path.exists(data_dir) is False:
    os.mkdir(data_dir)

#
# 3. Update nbconvert configuration
#
json_config = os.path.join(jupyter_config_dir(),
                           'jupyter_nbconvert_config.json')
print("Configuring %s" % json_config)
if os.path.isfile(json_config) is True:
    cl = JSONFileConfigLoader(json_config)
    config = cl.load_config()
else:
    config = Config()
newconfig = Config()
# Set template path, pre- and postprocessors of notebook extensions
newconfig.Exporter.template_path = ['.', os.path.join(data_dir, 'templates')]

config.merge(newconfig)
config.version = 1
s = json.dumps(config, indent=2, separators=(',', ': '), sort_keys=True)
with open(json_config, 'w') as f:
    f.write(s)

py_config = os.path.join(jupyter_config_dir(), 'jupyter_nbconvert_config.py')
print("Configuring %s" % py_config)