这是jupyter notebook 插件开发的系列文档之一, 文章最末尾列出了这个系列的所有博客连接.
什么是内容API
Jupyter Notebook Web应用程序提供了一个用于在虚拟文件系统中创建/打开/重命名和删除文件的图形界面。
ContentsManager类定义了一个抽象API,用于将这些交互转换为特定存储介质上的操作。默认的FileContentsManager使用服务器的本地文件系统进行存储,并直接将笔记本序列化为JSON。用户可以通过提供ContentsManager的自定义子类来覆盖这些行为。
本节介绍ContentsManager子类实现的接口。我们把这个接口称为Contents API。
数据模型
文件系统实体
ContentsManager将虚拟文件系统实体表示为字典,我们称之为模型。
模型可能包含以下条目:
| Key | Type | Info |
|---|---|---|
| name | unicode | Basename of the entity. |
| path | unicode | Full (API-style) path to the entity. |
| type | unicode | The entity type. One of
"notebook", "file" or
"directory". |
| created | datetime | Creation date of the entity. |
| last_modified | datetime | Last modified date of the entity. |
| content | variable | The “content” of the entity. (See Below) |
| mimetype | unicode or
None |
The mimetype of content,
if any. (See
Below) |
| format | unicode or
None |
The format of content,
if any. (See
Below) |
根据模型的类型字段,某些模型字段在结构上会有所不同。有三种模型类型:笔记本,文件和目录。
-
notebookmodels
-format字段总是json。
-mimetype字段总是None。
-content字段包含一个:class:nbformat.notebooknode.NotebookNode代表.pynb文件的类. 请参阅NBFormat文档描述。 -
filemodels
-format字段可以是"text"or"base64".
- 对于文本格式mimetype字段是text/plain,
base64格式是application/octet-stream。
-content”字段始终为unicode类型。对于文本格式
文件模型,content只是解码后的文件字节
作为UTF-8。非文本(base64)文件读取为字节,base64编码,
然后解码为UTF-8。 -
directorymodels
-format字段总是json。
-mimetype字段总是“None”。
-content字段包含一个content-free模型列表,
表示目录中的实体的模型。
注意:
在某些情况下,我们不需要实体的完整内容来完成内容API请求。在这种情况下,我们会忽略模型中的mimetype,content和format键。这在列出目录时最常出现,在这种情况下,我们将目录中的文件表示为无内容模型,以避免必须递归遍历并序列化整个文件系统。
案例
1 | # Notebook Model with Content |
API path
ContentsManager将文件系统资源的位置表示为API样式的路径。这些路径被解释为相对于笔记本服务器的根目录。为了跨系统兼容,需要做出以下保证:
- 路径总是“unicode”,而不是“bytes”。
- 路径不是URL转义的。
- 路径始终是正斜杠(/)分隔,即使在Windows上也是如此。
- 前后斜杠被剥离。例如
/ foo / bar / buzz /成为foo / bar / buzz。 - 空字符串(
"")表示根目录。
编写一个自定义ContentsManager
默认的ContentsManager是为在个人计算机上运行笔记本作为应用程序的用户而设计的。它将笔记本作为.ipynb文件存储在本地文件系统中,并将Notebook UI中的文件和目录映射到磁盘上的文件和目录。通过实现ContentsManager的自定义子类,可以重写笔记本的存储方式。例如,如果您在不信任或无法访问笔记本服务器文件系统的环境中部署笔记本,则可以编写自己的ContentsManager,将笔记本和文件存储在数据库中。
Required Methods
自定义ContentsManager的最小完整实现必须实现以下方法:
ContentsManager.get(path[, content, type, …]) |
Get a file or directory model. |
ContentsManager.save(model, path) |
Save a file or directory model to path. |
ContentsManager.delete_file(path) |
Delete the file or directory at path. |
ContentsManager.rename_file(old_path, new_path) |
Rename a file or directory. |
ContentsManager.file_exists([path]) |
Does a file exist at the given path? |
ContentsManager.dir_exists(path) |
Does a directory exist at the given path? |
ContentsManager.is_hidden(path) |
Is path a hidden directory or file? |
jupyter notebook 扩展开发系列:
- jupyter notebook 扩展开发之自定义请求处理程序
- jupyter notebook 扩展开发之内容API
- jupyter notebook 扩展开发之 Custom bundler extensions
- jupyter notebook 扩展开发之 文件保存钩子
- jupyter notebook扩展开发之前端插件开发
- jupyter notebook 扩展开发之 将Jupyter扩展作为Python包分发
转载请注明出处:http://mlln.cn 或者 http://jupyter.cn