繁体   English   中英

使用 nbformat 生成 Jupyter 笔记本 - Altair 图表不显示

[英]Generating Jupyter notebook with nbformat - Altair charts not displaying

我正在尝试以编程方式生成笔记本,执行它,然后使用 nbformat 转换为 HTML。

代码基本上是这样的:

import nbformat as nbf 
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert import HTMLExporter
 
nb = nbf.v4.new_notebook()
nb.cells = [nbf.v4.new_code_cell("""
   import altair as alt
   alt.renderers.enable("notebook")
   # ... load df
   alt.Chart(df).mark_point().encode(x='x', y='y')
""")]

ep = ExecutePreprocessor(timeout=600, kernel_name='python3')
ep.preprocess(nb, {'metadata': {'path': '.'}})

html_exporter = HTMLExporter()      
html_exporter.template_file = 'basic'
(body, resources) = html_exporter.from_notebook_node(nb)
with open('out.html', 'w') as f:
    f.write(body)

该流程运行良好,它生成一个笔记本和一个 HTML 文件,并且所有代码都已执行。 但是,代码单元的 output 如下(无图表):

<vega.vegalite.VegaLite at 0x7f80c4d8a090>

当我将 notebook 写为 .ipynb 文件并手动执行时,在相同的环境中,图表按预期显示。 是否可以通过这种方式使用 Altair? 我想知道我在 Python session 中运行 nbformat 的事实是否有所不同,也许它只能在浏览器中呈现图表?

通过 nbformat 生成笔记本和实时运行笔记本之间的区别在于 nbformat 没有附加前端。 这在这里很重要,因为对于 Altair 图表,前端笔记本扩展是呈现图表的内容。

那么为什么在生成后打开笔记本时渲染的图表不显示呢? It's because of the security model of the Jupyter notebook: the notebook will not execute existing Javascript when opening a new untrusted notebook, because this would be an easy attack path (eg an attacker could publish a notebook with javascript that, on load, executes python在您有机会阅读笔记本内容之前搜索您的硬盘驱动器以获取敏感信息并将其邮寄给攻击者的代码)。

出于这个原因,在渲染图表时,vega notebook 扩展程序会生成一个 PNG 预览并将其保存到 notebook 中,因此当你与其他人共享它时,他们会得到一个 static 图表预览作为占位符,直到他们实际执行 notebook。 但是,如果您在没有前端的情况下执行 notebook,则不会生成此 PNG 预览,因此在打开 notebook 时您什么也看不到。

解决此问题的最佳方法是使用 JupyterLab 而不是 Juptyer Notebook。 在 JupyterLab 中,Altair 图表使用 VegaLite Mimetype 保存,由 vega labextension 解释并转换为图表。 这不涉及从笔记本执行任意 javascript,因此您以这种方式创建的图表将在 JupyterLab 加载时在笔记本中呈现。 这个路径在经典笔记本中没有使用,因为经典不支持基于 mimebundle 的渲染。

如果您必须使用 Jupyter Notebook 而不是 JupterLab,那么除了可能使用无头浏览器引擎(例如selenium)以编程方式使用将呈现 PNG 预览的浏览器前端来执行您的笔记本之外,实际上没有任何方法可以解决此问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM