导入 iPython 自定义小部件功能(文件结构?)

Import a iPython Custom Widget Function (File Structure?)

我正在尝试遵循 this example and this tutorial to make a D3 widget which displays D3 HTML code to a widget when a function is called. I was able to make it function within the notebook cells itself using %%javascript,但这对最终用户来说会很麻烦。

如何将 Python D3Widget class 定义和 Javascript D3View 渲染代码移动到外部文件,以便用户可以简单地导入文件并调用函数?

我希望最终结果看起来像 this,用户可以简单地导入一个函数并调用它。

整理代码

在您的笔记本根文件夹中为您的新小部件创建一个包。例如,您可以使用以下目录结构:

helloworld/

    __init__.py
    helloworld_widget.py

    helloworldjs/
        helloworld.view.js

        css/
            helloworld.css

服务器端编程

在 helloworld/helloworld_widget.py 里面,把你的 Python class:

from ipywidgets import widgets
from traitlets import Unicode

class HelloWorldWidget(widgets.DOMWidget):
    _view_module = Unicode("nbextensions/helloworld/helloworld_view", sync=True)
    _view_name = Unicode('HelloWorldView', sync=True)

这就是您的 python 代码。

创建 Javascript 视图

在 helloworld/helloworldjs/helloworld.view.js 中对您的客户端进行编程:

define(["nbextensions/widgets/widgets/js/widget"], function(widget) {

    var HelloWorldView = widget.DOMWidgetView.extend({

        render: function(){
            this.$el.text("Hello world");
        },
    });

    return {HelloWorldView: HelloWorldView}
});

很简单,不是吗?最后但同样重要的是...

将客户端部署到笔记本的扩展文件夹

为此,您可以在 init.py 中编写一个函数,并在您每次在 Javascript 视图中修改某些内容时在笔记本中执行它。

我使用的这个与以下非常相似:

def notebook_install(overwrite=True, user=True):
    import os
    from notebook import install_nbextension
    from notebook.services.config import ConfigManager
    from IPython.display import display, Javascript

    js_path = os.path.join( os.path.dirname(__file__), 'helloworldjs')
    install_nbextension(js_path, overwrite=overwrite,
                        symlink=False, verbose=0, user=user)

现在您应该可以在笔记本中执行以下操作:

from helloworld.helloworld_widget import HelloWorldWidget
hello = HellowWorldWidget()
hello

尽情享受吧!

仔细阅读这篇文章应该也会有所帮助:https://carreau.gitbooks.io/jupyter-book/content/notebook-extensions.html