最近工作需要实现对Jupyter实现二次开发,自定义一些功能,因此记录一下。
大致需求为:自定义些页面获取参数,根据参数从数据库中获取数据转pandas格式给notebook页面,因此需做个自动生成代码的功能。
需用到以下相关的方法
前端代码写入
前端获取选择的代码块
c = IPython.notebook.get_selected_cell()
前端获取代码块的内容
c.get_text()
前端设置代码块的内容
code = "print'1'"
c.set_text(code)
后端代码生成
import nbformat
code = "print('hello world')"
# 转成notebook类型的代码格式
cell = nbformat.v4.new_code_cell(code)
print(cell)
# {'cell_type': 'code', 'metadata': {}, 'execution_count': None, 'source': 'print(1)', 'outputs': []}
案例
前端JS
$("#getEventDataSet").click(function () {
// 获取到选择的代码块
var cell = IPython.notebook.get_selected_cell()
var xsrf = getCookie("_xsrf")
var data = {
// 传参相关。。。
}
$.ajax({
headers: {"X-XSRFToken": xsrf},
type: "POST",
dataType: "json",
async: false,
url: "/action/getEvent",
data: JSON.stringify(data),
success: function (result) {
console.log(result);
if (result.success) {
// 取出代码内容并通过set_text写入
var code = result.new_cell.source
// 如果不想覆盖,可以先get_text获取原内容处理后在写
cell.set_text(code)
}
}
})
})
后端相关
class GetEventDataSet(APIHandler):
@web.authenticated
@gen.coroutine
def post(self, *args, **kwargs):
code = """print('hello world')"""
ncc = nbformat.v4.new_code_cell(code)
self.write({"success": True, "new_cell": ncc})
# -----------------------------------------------------------------------------
# URL to handler mappings
# -----------------------------------------------------------------------------
# 绑定路由
default_handlers = [
(r"/action/getEvent", GetEventDataSet),
]