notebook/docs/source/examples/Notebook/Distributing Jupyter Extensions as Python Packages.ipynb
Afshin Taylor Darian c19323de9a
Use Jupyter Releaser (#6048)
* Use Jupyter Releaser

* Automated Changelog Entry for 6.4.0a0 on notebook-releaser

* Publish 6.4.0a0

SHA256 hashes:

dist/notebook-6.4.0a0-py3-none-any.whl: abbbbb02504cedb85c2d5eeac39ea11615360b9b0075126bf180d6011eac14a5

dist/notebook-6.4.0a0.tar.gz: 2984630a020a9396c61b2c3b98f43b1957dd0121b162a926b3d6136fafa7ca16

* Bump to 6.5.0.dev0

* Remove jupyter_packaging as a runtime requirement

* Automated Changelog Entry for 6.4.0a1 on notebook-releaser

* Publish 6.4.0a1

SHA256 hashes:

dist/notebook-6.4.0a1-py3-none-any.whl: 4b0ae5cb972b5b16b18b942810b85859185ef2081017dd495e5f57099ce06ef4

dist/notebook-6.4.0a1.tar.gz: c48e10d34afa35e304e3b7deca1882508195960f35c4661dec044bb8da344ae5

* Bump to 6.5.0.dev0

* Update notebook/_version.py

Co-authored-by: Kevin Bates <kbates4@gmail.com>

* Update pyproject.toml

Co-authored-by: Kevin Bates <kbates4@gmail.com>

Co-authored-by: GitHub Action <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Steven Silvester <steven.silvester@ieee.org>
Co-authored-by: Kevin Bates <kbates4@gmail.com>
2021-05-12 11:04:31 -05:00

17 KiB

Distributing Jupyter Extensions as Python Packages

Overview

How can the notebook be extended?

The Jupyter Notebook client and server application are both deeply customizable. Their behavior can be extended by creating, respectively:

  • nbextension: a notebook extension
    • a single JS file, or directory of JavaScript, Cascading StyleSheets, etc. that contain at minimum a JavaScript module packaged as an AMD modules that exports a function load_ipython_extension
  • server extension: an importable Python module
    • that implements load_jupyter_server_extension
  • bundler extension: an importable Python module with generated File -> Download as / Deploy as menu item trigger
    • that implements bundle

Why create a Python package for Jupyter extensions?

Since it is rare to have a server extension that does not have any frontend components (an nbextension), for convenience and consistency, all these client and server extensions with their assets can be packaged and versioned together as a Python package with a few simple commands, or as of Notebook 5.3, handled automatically by your package manager of choice. This makes installing the package of extensions easier and less error-prone for the user.

Installation of Jupyter Extensions

Install a Python package containing Jupyter Extensions

There are several ways that you may get a Python package containing Jupyter Extensions. Commonly, you will use a package manager for your system:

pip install helpful_package
# or
conda install helpful_package
# or
apt-get install helpful_package

# where 'helpful_package' is a Python package containing one or more Jupyter Extensions

Automatic installation and Enabling

New in Notebook 5.3

The absolute simplest case requires no user interaction at all! Configured correctly, after installing with their package manager of choice, both server and frontend extensions can be enabled by default in the environment where they were installed, i.e. --sys-prefix. See the setup.py in the example below.

Enable a Server Extension

The simplest case would be to enable a server extension which has no frontend components.

A pip user that wants their configuration stored in their home directory would type the following command:

jupyter serverextension enable --py helpful_package

Alternatively, a virtualenv or conda user can pass --sys-prefix which keeps their environment isolated and reproducible. For example:

# Make sure that your virtualenv or conda environment is activated
[source] activate my-environment

jupyter serverextension enable --py helpful_package --sys-prefix

Install the nbextension assets

If a package also has an nbextension with frontend assets that must be available (but not neccessarily enabled by default), install these assets with the following command:

jupyter nbextension install --py helpful_package # or --sys-prefix if using virtualenv or conda

Enable nbextension assets

If a package has assets that should be loaded every time a Jupyter app (e.g. lab, notebook, dashboard, terminal) is loaded in the browser, the following command can be used to enable the nbextension:

jupyter nbextension enable --py helpful_package # or --sys-prefix if using virtualenv or conda

Did it work? Check by listing Jupyter Extensions.

After running one or more extension installation steps, you can list what is presently known about nbextensions, server extensions, or bundler extensions. The following commands will list which extensions are available, whether they are enabled, and other extension details:

jupyter nbextension list
jupyter serverextension list
jupyter bundlerextension list

Additional resources on creating and distributing packages

How you distribute them, too, is important:

Of course, in addition to the files listed, there are number of other files one needs to build a proper package. Here are some good resources:

Example - Server extension

Creating a Python package with a server extension

Here is an example of a python module which contains a server extension directly on itself. It has this directory structure:

- setup.py
- MANIFEST.in
- my_module/
  - __init__.py

Defining the server extension

This example shows that the server extension and its load_jupyter_server_extension function are defined in the __init__.py file.

my_module/__init__.py

def _jupyter_server_extension_paths():
    return [{
        "module": "my_module"
    }]


def load_jupyter_server_extension(nbapp):
    nbapp.log.info("my module enabled!")

Install and enable the server extension

Which a user can install with:

jupyter serverextension enable --py my_module [--sys-prefix]

Example - Server extension and nbextension

Creating a Python package with a server extension and nbextension

Here is another server extension, with a front-end module. It assumes this directory structure:

- setup.py
- MANIFEST.in
- my_fancy_module/
  - __init__.py
  - static/
    index.js

Defining the server extension and nbextension

This example again shows that the server extension and its load_jupyter_server_extension function are defined in the __init__.py file. This time, there is also a function _jupyter_nbextension_paths for the nbextension.

my_fancy_module/__init__.py

def _jupyter_server_extension_paths():
    return [{
        "module": "my_fancy_module"
    }]

# Jupyter Extension points
def _jupyter_nbextension_paths():
    return [dict(
        section="notebook",
        # the path is relative to the `my_fancy_module` directory
        src="static",
        # directory in the `nbextension/` namespace
        dest="my_fancy_module",
        # _also_ in the `nbextension/` namespace
        require="my_fancy_module/index")]

def load_jupyter_server_extension(nbapp):
    nbapp.log.info("my module enabled!")

Install and enable the server extension and nbextension

The user can install and enable the extensions with the following set of commands:

jupyter nbextension install --py my_fancy_module [--sys-prefix|--user]
jupyter nbextension enable --py my_fancy_module [--sys-prefix|--system]
jupyter serverextension enable --py my_fancy_module [--sys-prefix|--system]

Automatically enabling a server extension and nbextension

New in Notebook 5.3

Server extensions and nbextensions can be installed and enabled without any user intervention or post-install scripts beyond <package manager> install <extension package name>

In addition to the my_fancy_module file tree, assume:

jupyter-config/
├── jupyter_notebook_config.d/
│   └── my_fancy_module.json
└── nbconfig/
    └── notebook.d/
        └── my_fancy_module.json

jupyter-config/jupyter_notebook_config.d/my_fancy_module.json

{
  "NotebookApp": {
    "nbserver_extensions": {
      "my_fancy_module": true
    }
  }
}

jupyter-config/nbconfig/notebook.d/my_fancy_module.json

{
  "load_extensions": {
    "my_fancy_module/index": true
  }
}

Put all of them in place via:

setup.py

import setuptools

setuptools.setup(
    name="MyFancyModule",
    ...
    include_package_data=True,
    data_files=[
        # like `jupyter nbextension install --sys-prefix`
        ("share/jupyter/nbextensions/my_fancy_module", [
            "my_fancy_module/static/index.js",
        ]),
        # like `jupyter nbextension enable --sys-prefix`
        ("etc/jupyter/nbconfig/notebook.d", [
            "jupyter-config/nbconfig/notebook.d/my_fancy_module.json"
        ]),
        # like `jupyter serverextension enable --sys-prefix`
        ("etc/jupyter/jupyter_notebook_config.d", [
            "jupyter-config/jupyter_notebook_config.d/my_fancy_module.json"
        ])
    ],
    ...
    zip_safe=False
)

and last, but not least:

MANIFEST.in

config
recursive-include jupyter-config *.json
recursive-include my_fancy_module/static *.js

As most package managers will only modify their environment, the eventual configuration will be as if the user had typed:

jupyter nbextension install --py my_fancy_module --sys-prefix
jupyter nbextension enable --py my_fancy_module --sys-prefix
jupyter serverextension enable --py my_fancy_module --sys-prefix

If a user manually disables an extension, that configuration will override the bundled package configuration.

When automagical install fails

Note this can still fail in certain situations with pip, requiring manual use of install and enable commands.

Non-python-specific package managers (e.g. conda, apt) may choose not to implement the above behavior at the setup.py level, having more ways to put data files in various places at build time.

Example - Bundler extension

Creating a Python package with a bundlerextension

Here is a bundler extension that adds a Download as -> Notebook Tarball (tar.gz) option to the notebook File menu. It assumes this directory structure:

- setup.py
- MANIFEST.in
- my_tarball_bundler/
  - __init__.py

Defining the bundler extension

This example shows that the bundler extension and its bundle function are defined in the __init__.py file.

my_tarball_bundler/__init__.py

import tarfile
import io
import os
import nbformat

def _jupyter_bundlerextension_paths():
    """Declare bundler extensions provided by this package."""
    return [{
        # unique bundler name
        "name": "tarball_bundler",
        # module containing bundle function
        "module_name": "my_tarball_bundler",
        # human-readable menu item label
        "label" : "Notebook Tarball (tar.gz)",
        # group under 'deploy' or 'download' menu
        "group" : "download",
    }]


def bundle(handler, model):
    """Create a compressed tarball containing the notebook document.
    
    Parameters
    ----------
    handler : tornado.web.RequestHandler
        Handler that serviced the bundle request
    model : dict
        Notebook model from the configured ContentManager
    """
    notebook_filename = model['name']
    notebook_content = nbformat.writes(model['content']).encode('utf-8')
    notebook_name = os.path.splitext(notebook_filename)[0]
    tar_filename = '{}.tar.gz'.format(notebook_name)
    
    info = tarfile.TarInfo(notebook_filename)
    info.size = len(notebook_content)

    with io.BytesIO() as tar_buffer:
        with tarfile.open(tar_filename, "w:gz", fileobj=tar_buffer) as tar:
            tar.addfile(info, io.BytesIO(notebook_content))
        
        # Set headers to trigger browser download
        handler.set_header('Content-Disposition',
                           'attachment; filename="{}"'.format(tar_filename))
        handler.set_header('Content-Type', 'application/gzip')
                
        # Return the buffer value as the response
        handler.finish(tar_buffer.getvalue())

See Extending the Notebook for more documentation about writing nbextensions, server extensions, and bundler extensions.