Beispiel #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()
Beispiel #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()
Beispiel #3
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)
Beispiel #4
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)
Beispiel #5
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()
Beispiel #7
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
Beispiel #8
0
    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)))
Beispiel #9
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
Beispiel #10
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
Beispiel #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
Beispiel #12
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
Beispiel #13
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
Beispiel #14
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
    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)))
Beispiel #16
0
    def test_context_manager(self):

        fd, fname = mkstemp(".json", prefix="μnïcø∂e")
        f = os.fdopen(fd, "w")
        f.write("{}")
        f.close()

        cl = JSONFileConfigLoader(fname, log=log)

        value = "context_manager"

        with cl as c:
            c.MyAttr.value = value

        self.assertEqual(cl.config.MyAttr.value, value)

        # check that another loader does see the change
        _ = JSONFileConfigLoader(fname, log=log)
        self.assertEqual(cl.config.MyAttr.value, value)
Beispiel #17
0
    def test_context_manager(self):

        fd, fname = mkstemp('.json', prefix=u'μnïcø∂e')
        f = os.fdopen(fd, 'w')
        f.write('{}')
        f.close()

        cl = JSONFileConfigLoader(fname, log=log)

        value = 'context_manager'

        with cl as c:
            c.MyAttr.value = value

        self.assertEqual(cl.config.MyAttr.value, value)

        # check that another loader does see the change
        cl2 = JSONFileConfigLoader(fname, log=log)
        self.assertEqual(cl.config.MyAttr.value, value)
Beispiel #18
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_server_config.json', jupyter_config_dir())
    try:
        config = loader.load_config()
    except ConfigFileNotFound:
        config = Config()

    yield config

    filepath = os.path.join(jupyter_config_dir(), 'jupyter_server_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")
Beispiel #19
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")
Beispiel #20
0
def load_jupytext_configuration_file(jupytext_config_file):
    """Read a Jupytext config file, and return a JupytextConfig object"""

    if jupytext_config_file.endswith((".toml", "jupytext")):
        import toml

        config = toml.load(jupytext_config_file)
        return JupytextConfiguration(**config)

    if jupytext_config_file.endswith((".yml", ".yaml")):
        with open(jupytext_config_file) as stream:
            config = yaml.safe_load(stream)
        return JupytextConfiguration(**config)

    if jupytext_config_file.endswith(".py"):
        return JupytextConfiguration(
            **PyFileConfigLoader(jupytext_config_file).load_config())

    return JupytextConfiguration(
        **JSONFileConfigLoader(jupytext_config_file).load_config())
Beispiel #21
0
 def load(self):
     loader = JSONFileConfigLoader(self.__config_path.name,
                                   str(self.__config_path.parent.resolve()))
     self.__config = loader.load_config()
Beispiel #22
0
        cert.sign(k, "sha256")

        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?")
print("Extensions and templates path: %s" % data_dir)

# 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)
Beispiel #24
0
                                        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()
recursive_overwrite(src, destination)

# 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')