[英]How to create a new jupyter notebook cell and update the cell using notebook server rest api's or python code?
我是 python 編碼的新手。我能夠使用 jupyter 筆記本服務器 rest api 創建 new.ipynb 文件。
我正在使用以下 curl 命令使用 rest api 創建一個 new.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 服務器 rest api 或使用 python 代碼創建一個新的 jupyter notebook 單元,並使用基本打印語句更新單元。 但拿不到。 有誰知道如何解決這個問題?
提前致謝!
我使用以下代碼完成了任務:創建新筆記本:
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")
def write_file_remotely(self, filename):
"""Creates a new .remote ipynb file which will be used for testing."""
# https://jupyter-server.readthedocs.io/en/latest/developers/rest-api.html#put--api-contents-path
notebook_file_name = os.path.basename(filename)
body = {
"content": {
"cells": [{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": ['print("Hello Notebooks!")']
}],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 4
},
"format": "json",
"name": f"{notebook_file_name}",
"path": f"{notebook_file_name}",
"type": "notebook",
}
# pylint: enable=g-inconsistent-quotes
print(f'Creating a new Notebook file: {notebook_file_name}')
print(body)
try:
# Check: c.ServerApp.disable_check_xsrf setting.
response = self._session.put(
f'{self.url}/api/contents/{notebook_file_name}',
timeout=HTTP_TIMEOUT_SESSION,
auth=BearerAuth(self._token),
json=body)
response.raise_for_status()
return True
except requests.exceptions.HTTPError as err:
print(response.status_code)
http_code = err.response.status_code
if http_code == 404:
print(f'{self.url} HTTP: {http_code}')
return False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.