Skip to content

Instantly share code, notes, and snippets.

@minrk
Created July 25, 2017 16:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save minrk/3045784d928a98c445ed997cb6b55c62 to your computer and use it in GitHub Desktop.
Save minrk/3045784d928a98c445ed997cb6b55c62 to your computer and use it in GitHub Desktop.
"""
Python implementation of https://github.com/jupyterhub/jupyterhub/issues/1261
"""
import json
import requests
username = 'minrk'
password = 'secret'
hub_url = 'http://127.0.0.1:8765'
login_url = hub_url + '/hub/login'
token_url = hub_url + '/hub/api/authorizations/token'
# step 1: login with username + password
r = requests.post(login_url, data={'username': username, 'password': password}, allow_redirects=False)
r.raise_for_status()
cookies = r.cookies
# 2. request token
r = requests.post(token_url,
headers={'Referer': login_url},
cookies=cookies,
)
r.raise_for_status()
token = r.json()['token']
auth_headers = {'Authorization': 'token %s' % token}
# 3. check if running, spawn if not
url = None
while url is None:
r = requests.get(hub_url + '/hub/api/users/%s' % username, headers=auth_headers)
r.raise_for_status()
status = r.json()
url = status['server']
if not url and not status['pending']:
r = requests.post(hub_url + '/hub/api/users/%s/server' % username, headers=auth_headers)
r.raise_for_status()
# 4. talk to the contents service
r = requests.get(hub_url + url + '/api/contents/', headers=auth_headers, allow_redirects=False)
r.raise_for_status()
print(json.dumps(r.json(), sort_keys=True, indent=1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment