Reputation: 2137
A friend is trying to run a script to check which notebooks are using the most memory, but their server is password protected. I'm trying to figure out how to configure authentication using urllib2
since I don't believe there is a username, only a password.
Upvotes: 1
Views: 2220
Reputation: 1
i found when use jupyter put api upload file response 403,
need add "X-XSRFToken" header can solve it..
data= json.dumps({
"name": "test.jpg",
"path": "path",
"type":"file",
"format": "base64",
"content": "base64 data"
})
headers["X-XSRFToken"] = xsrf_cookie
s.put(url, data=data, headers=headers)
Upvotes: 0
Reputation: 598
It seems there are some changes with new version. url '/login' does not work for me, I need to add next
parameters
url='http://localhost:8050/login?next=%2F'
For the login request. The rest just like Hassan answer
Upvotes: 1
Reputation: 396
The @aiguofer answer did not work for me because jupyter now uses '_xsrf' in cookie. The follwoing woked for me:
s = requests.Session()
url='http://127.0.0.1:8888/login/'
resp=s.get(url)
xsrf_cookie = resp.cookies['_xsrf']
params={'_xsrf':xsrf_cookie,'password': password}
s.post(url, data=params)
After that s
can be used to call the apis.
Upvotes: 1
Reputation: 2137
After digging into the notebook code and through some trial and error, I figured out how to do this (and I switched to using requests
).
I can't guarantee that this is the best way to do it, but it certainly worked for me. I actually set my vars elsewhere in the code but included here for completeness
import requests
hostname = '127.0.0.1'
port = '8888'
password = 'mypassword'
base_url = 'http://{0}:{1}/'.format(hostname, port)
h = {}
if password:
r = requests.post(base_url + 'login', params={
'password': password
})
h = r.request.headers
sessions = requests.get(base_url + 'api/sessions', headers=h).json()
I believe this works because when you hit the /login
endpoint, it redirects you with the right headers set. I guess requests
keeps the headers of the redirect, so we can reuse those for the other call. It might be better to extract only the cookies and use those, but this works for now :)
Upvotes: 0