Skip to content

Instantly share code, notes, and snippets.

@Shaiken
Last active January 22, 2021 12:36
Show Gist options
  • Save Shaiken/b12fa71d4d0c39520cb5f3d44b01c0df to your computer and use it in GitHub Desktop.
Save Shaiken/b12fa71d4d0c39520cb5f3d44b01c0df to your computer and use it in GitHub Desktop.
Access Jupyter API for Python(使用Jupyter API 上傳檔案等)..
import requests
import os
import base64
import urllib.parse
import json
import socket
def jupyter_uploadfile(theport, filePath, resourceDstPath):
'''
param:
theport: port
filePath: 照片路徑
resourceDstPath: jupyter路徑不包含照片檔名
'''
hostname = 'xx.xx.xx.xx'
password = 'xx'
# 此處注意自己的jupyter登入路徑是什麼, 我的IP後方是jupyter
base_url = 'http://{0}/jupyter/'.format(hostname)
#此處也是這邊自己的格式, 請看自己login那頁
login_url = base_url + 'login?n=' + str(theport)
api_contents_url= base_url + "api/contents/想要知道的jupyter路徑/"
req_session = requests.Session()
res = req_session.get(login_url)
xsrf_cookie = res.cookies['_xsrf']
params={'_xsrf':xsrf_cookie,'password': password}
#網路有資訊說可以藉由 req_session 存取api, 但實際測試put無法實現
res = req_session.post(login_url, data=params)
#取得某資料夾路徑的資訊
res = req_session.get(api_contents_url)
fileName = filePath[1 + filePath.rfind(os.sep):]
resourceDstPath = resourceDstPath + fileName
api_contents_url = base_url + "api/contents/" + resourceDstPath
with open(filePath, 'rb') as myfile:
data=myfile.read()
b64data=base64.b64encode(data)
#此處我讀.jpg時有多了b'xxxxxxxxx', 所以把b''去掉
b64data = str(b64data).split('\'')[1]
body = json.dumps({
"name": fileName,
"path": resourceDstPath,
"type":"file",
"format": "base64",
"content": b64data
})
#重點在這邊, 需要加X-XSRFToken header, 用postman測出來的
headers = {}
headers["X-XSRFToken"] = xsrf_cookie
res = req_session.put(api_contents_url, data=body, headers=headers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment