【问题标题】:How to create a new jupyter notebook cell and update the cell using notebook server rest api's or python code?如何创建一个新的 jupyter 笔记本单元并使用笔记本服务器 rest api 或 python 代码更新单元?
【发布时间】:2020-01-24 13:13:12
【问题描述】:

我是 python 编码的新手。我能够使用 jupyter notebook 服务器 rest api 创建新的 .ipynb 文件。

我正在使用下面的 curl 命令使用其余的 api 创建一个新的 .ipynb 文件,

curl -X PUT "http://localhost:8890/api/contents/two.ipynb" -H "accept: application/json" -H "Authorization: Token xxxxxxxx" -d "{\"name\": \"one.ipynb\"}"

现在,我正在尝试使用 jupyter notebook server rest api 或使用 python 代码创建一个新的 jupyter notebook 单元,并使用基本打印语句更新单元。但拿不到。有人知道怎么解决吗?

提前致谢!

【问题讨论】:

    标签: python jupyter-notebook


    【解决方案1】:

    我使用以下代码完成了任务: 创建新笔记本:

    import requests
    import nbformat as nbf
    import sys
    from nbconvert.preprocessors import ExecutePreprocessor
    import json
    import os
    
    def create_nb():
    api_url =  'http://192.168.1.xxx:8890/api/contents/root/ppl'
    headers = {'token': 'token_passwd'}
    headers1 = {'Authorization': 'Token token_passwd'}
    body={"type": "notebook"}
    
    result = requests.post(api_url,headers=headers1,json=body)
    output=result.json()
    
    return('/'+output["path"])
    

    在指定路径中创建一个新单元格:

    def create_cell(path,session_id):
    
    head,file_name = os.path.split(path)
    file_path=path[1:]
    
    api_url =  'http://192.168.1.126:8890/api/sessions/'+session_id
    headers1 = {'Authorization': 'Token token_passwd','Content-Type': 'application/json'}
    body={"name":file_name, "type": "notebook","path": file_path,"kernel": {"name": "python3"}}
    #result = requests.post(api_url,headers=headers1,json=body)
    
    present_id=requests.get(api_url,headers=headers1)
    #print("present_id ---->>> "+present_id.json()["id"])
    nb1 = nbf.read(path, as_version=4)
    code=""""""
    nb1['cells']= nb1['cells']+[nbf.v4.new_code_cell(code)]
    with open(path, "w") as f:
        nbf.write(nb1, f)
    
    return("cell created")
    

    【讨论】:

    • 有没有其他的 api 来运行你制作的单元???
    猜你喜欢
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 2021-12-31
    相关资源
    最近更新 更多