Skip to content

Instantly share code, notes, and snippets.

@snickell
Last active April 20, 2020 23:59
Show Gist options
  • Save snickell/b29a189c56ad1833a8ee8061b34e12d0 to your computer and use it in GitHub Desktop.
Save snickell/b29a189c56ad1833a8ee8061b34e12d0 to your computer and use it in GitHub Desktop.
Gets a reference to the current Jupyter Notebook and Server when run inside a Cell (also works for JupyterLab), can map kernel relative paths to files_urls
from pathlib import Path
import re
import requests
from urllib.parse import urljoin
import ipykernel
from notebook.notebookapp import list_running_servers
def files_url_for(kernel_path):
_server = server()
path_of_base_url = _server['notebook_dir']
return urljoin(
_files_base_url(_server),
str(Path(kernel_path).resolve().relative_to(path_of_base_url))
)
def notebook():
return _current_jupyter()['notebook']
def server():
return _current_jupyter()['server']
def _files_base_url(server):
return urljoin(
server['url'],
# TODO: this is a hacky whacky assumption... 🤦‍♀️
# what's the least unprincipled way to do this?
f'files/'
)
def _current_jupyter():
kernel_id = _current_kernel_id()
return next((
{
'notebook': notebook,
'server': server
}
for notebook, server in _all_notebooks()
if notebook['kernel']['id'] == kernel_id
))
def _api_url(server, api_name):
return urljoin(server['url'], f'api/{api_name}')
def _all_notebooks():
def get_session(server):
session_url = urljoin(server['url'], 'api/sessions')
token_param = {
'token': server.get('token', '')
}
sessions_url = _api_url(server, 'sessions')
return requests.get(sessions_url, token_param).json()
return (
( notebook, server )
for notebooks, server in (
( get_session(server), server ) for server in list_running_servers()
)
for notebook in notebooks
)
def _current_kernel_id():
connections = ipykernel.connect.get_connection_file()
return re.search('kernel-(.*).json', connections).group(1)
@snickell
Copy link
Author

snickell commented Apr 20, 2020

from .current_jupyter import server, notebook, files_url_for
print(f"URL of the server is: {server()['url']}")
# => 'http://localhost:8888'

print(f"Path of the notebook is: {notebook()}")
# => 'src/noboo.ipynb'

print(f"Frontend URL for 'foobar.txt' is {files_url_for('foobar.txt')}")
# => 'http://localhost:8888/files/foobar.txt'

# maybe we're on jupyterhub, using jupyterlab, logged in as user 'seth'...
# lets say this works: 
f = open('mypath/somefile.txt')
# then you can get a URL to that file that can be used on the frontend like so:
print(f"The URL for path {f.name} is: {files_url_for(f.name)}")
# => 'http://juphub.mydomain.org:8888/user/seth/files/mypath/somefile.txt'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment