我正在尝试使用 Jupyter Rest API,使用在本地 Anaconda 上运行的 python 程序将文件传输到 docker 容器内的本地 Jupyter。
在稍微了解如何输入令牌之后,我已经成功执行了
requests.get()
。
现在我想执行
requests.post()
命令来传输文件。
配置:
代码:
token = token_code_provided_by_jupyter_at_startup
api_url = "http://192.168.99.100:8888/api/contents"
# getting the file's data from disk and converting into a json file
cwd = os.getcwd()
file_location = cwd+r'\Resources\Test\test_post.py'
payload = open(file_location, 'r').read()
b64payload = base64.encodestring(payload)
body = json.dumps({
'content':b64payload,
'name': 'test_post.py',
'path': '/api/contents/',
'format': 'base64',
'type':'file'
})
# getting the xsrf cookie
client = requests.session()
client.get('http://192.168.99.100:8888/')
csrftoken = client.cookies['_xsrf']
headers ={'Content-type': 'application/json', 'X-CSRFToken':csrftoken, 'Referer':'http://192.168.99.100:8888/api/contents', 'token':token}
response = requests.post(api_url, data=body, headers=headers, verify=True)
返回错误
[W 12:22:36.710 NotebookApp] 403 POST /api/contents (192.168.99.1): XSRF cookie does not match POST argument [W 12:22:36.713 NotebookApp] 403 POST /api/contents (192.168.99.1) 4.17ms referer=`http://192.168.99.100:8888/api/contents
实际上,使用 header token 进行身份验证时,不需要 xsrf cookie。
headers = {'Authorization': 'token ' + token}
参考 Jupyter Notebook 文档。
http://jupyter-notebook.readthedocs.io/en/latest/security.html
我的 JupyterHub 部署位于组织代理后面。将以下内容添加到我的
singleuser.extraEnv
文件中的 values.yaml
是对我有用的唯一修复:
extraEnv:
NO_PROXY: "<hub_url>,<hub-ip>,localhost,127.0.0.1"
no_proxy: "<hub_url>,<hub-ip>,localhost,127.0.0.1"
参考:https://jupyterhub.readthedocs.io/en/latest/faq/troubleshooting.html#proxy-settings-403-get
只需使用 jupyter 笔记本转到 Chrome 或默认浏览器设置即可。更改 cookie 设置以允许第三方 cookie。我想这会解决你的问题。