##// END OF EJS Templates
Fixes to make spinners in cluster list display correctly.
Fixes to make spinners in cluster list display correctly.

File last commit:

r16486:19651d21
r16922:31595470
Show More
filenbmanager.py
470 lines | 17.5 KiB | text/x-python | PythonLexer
MinRK
add utils.path.ensure_dir_exists...
r16486 """A notebook manager that uses the local file system for storage."""
Brian E. Granger
More review changes....
r4609
MinRK
add utils.path.ensure_dir_exists...
r16486 # Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
Brian E. Granger
Massive work on the notebook document format....
r4484
Thomas Kluyver
Save notebook as script using unicode file handle....
r6030 import io
Brian E. Granger
Massive work on the notebook document format....
r4484 import os
Stefan van der Walt
Move glob to global level import.
r4624 import glob
MinRK
add checkpoint API to FileNBManager
r10497 import shutil
Zachary Sailer
manual rebase notebooks web services
r12984
Brian E. Granger
Massive work on the notebook document format....
r4484 from tornado import web
Brian Granger
Renaming BaseNotebookManager->NotebookManager to preserve config.
r8194 from .nbmanager import NotebookManager
MinRK
move signature checking to base NotebookManager...
r14907 from IPython.nbformat import current
MinRK
add utils.path.ensure_dir_exists...
r16486 from IPython.utils.path import ensure_dir_exists
Thomas Kluyver
Fix a couple of static analysis warnings
r15526 from IPython.utils.traitlets import Unicode, Bool, TraitError
MinRK
reorganize who knows what about paths...
r15420 from IPython.utils.py3compat import getcwd
MinRK
add timezone info to `last_modified` in notebook managers...
r11145 from IPython.utils import tz
MinRK
reorganize who knows what about paths...
r15420 from IPython.html.utils import is_hidden, to_os_path
Brian E. Granger
Massive work on the notebook document format....
r4484
Thomas Kluyver
Case insensitive sorting in the dashboard....
r15523 def sort_key(item):
Thomas Kluyver
Don't attempt locale-aware sorting for now....
r15524 """Case-insensitive sorting."""
return item['name'].lower()
Thomas Kluyver
Case insensitive sorting in the dashboard....
r15523
Brian E. Granger
Massive work on the notebook document format....
r4484 #-----------------------------------------------------------------------------
Fernando Perez
Add --script flag as shorthand for the script autosave notebook option.
r5758 # Classes
#-----------------------------------------------------------------------------
Brian E. Granger
Massive work on the notebook document format....
r4484
Brian Granger
Renaming BaseNotebookManager->NotebookManager to preserve config.
r8194 class FileNotebookManager(NotebookManager):
MinRK
allow saving notebook.py next to notebook.ipynb...
r5653
save_script = Bool(False, config=True,
Fernando Perez
Fix typo in help string
r5760 help="""Automatically create a Python script when saving the notebook.
MinRK
allow saving notebook.py next to notebook.ipynb...
r5653
Matthias BUSSONNIER
remove references to loadpy...
r6765 For easier use of import, %run and %load across notebooks, a
Fernando Perez
Add --script flag as shorthand for the script autosave notebook option.
r5758 <notebook-name>.py script will be created next to any
<notebook-name>.ipynb on each save. This can also be set with the
short `--script` flag.
MinRK
allow saving notebook.py next to notebook.ipynb...
r5653 """
)
MinRK
reorganize who knows what about paths...
r15420 notebook_dir = Unicode(getcwd(), config=True)
MinRK
allow saving notebook.py next to notebook.ipynb...
r5653
MinRK
reorganize who knows what about paths...
r15420 def _notebook_dir_changed(self, name, old, new):
"""Do a bit of validation of the notebook dir."""
if not os.path.isabs(new):
# If we receive a non-absolute path, make it absolute.
self.notebook_dir = os.path.abspath(new)
return
if not os.path.exists(new) or not os.path.isdir(new):
raise TraitError("notebook dir %r is not a directory" % new)
MinRK
create checkpoints dir in notebook subdirectories
r16447
checkpoint_dir = Unicode('.ipynb_checkpoints', config=True,
help="""The directory name in which to keep notebook checkpoints
This is a path relative to the notebook's own directory.
MinRK
add checkpoint API to FileNBManager
r10497
MinRK
create checkpoints dir in notebook subdirectories
r16447 By default, it is .ipynb_checkpoints
MinRK
add checkpoint API to FileNBManager
r10497 """
)
MinRK
fallback on copy, copyfile if copy2 fails...
r15827
def _copy(self, src, dest):
"""copy src to dest
MinRK
only catch errors in copystat
r15865 like shutil.copy2, but log errors in copystat
MinRK
fallback on copy, copyfile if copy2 fails...
r15827 """
MinRK
only catch errors in copystat
r15865 shutil.copyfile(src, dest)
try:
shutil.copystat(src, dest)
except OSError as e:
self.log.debug("copystat on %s failed", dest, exc_info=True)
MinRK
fallback on copy, copyfile if copy2 fails...
r15827
MinRK
adjust definition of 'path' in notebooks...
r13067 def get_notebook_names(self, path=''):
Brian E. Granger
Review and refactoring of notebooks web service.
r13051 """List all notebook names in the notebook dir and path."""
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 path = path.strip('/')
MinRK
reorganize who knows what about paths...
r15420 if not os.path.isdir(self._get_os_path(path=path)):
Thomas Kluyver
404 on attempt to list notebooks in nonexistant directory
r13100 raise web.HTTPError(404, 'Directory not found: ' + path)
MinRK
reorganize who knows what about paths...
r15420 names = glob.glob(self._get_os_path('*'+self.filename_ext, path))
Zachary Sailer
manual rebase notebooks web services
r12984 names = [os.path.basename(name)
Stefan van der Walt
Allow period characters in notebook names.
r4623 for name in names]
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 return names
Zachary Sailer
Add 'patch' to session & notebook, rename working
r12997
MinRK
move os_path to FileNBMan...
r13070 def path_exists(self, path):
"""Does the API-style path (directory) actually exist?
Zachary Sailer
add tests to notebooks api...
r13059
MinRK
move os_path to FileNBMan...
r13070 Parameters
----------
path : string
The path to check. This is an API path (`/` separated,
relative to base notebook-dir).
Returns
-------
exists : bool
Whether the path is indeed a directory.
"""
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 path = path.strip('/')
MinRK
reorganize who knows what about paths...
r15420 os_path = self._get_os_path(path=path)
MinRK
move os_path to FileNBMan...
r13070 return os.path.isdir(os_path)
Brian E. Granger
Creating and testing IPython.html.utils.is_hidden.
r15097
def is_hidden(self, path):
"""Does the API style path correspond to a hidden directory or file?
Parameters
----------
path : string
The path to check. This is an API path (`/` separated,
relative to base notebook-dir).
Returns
-------
exists : bool
Whether the path is hidden.
"""
path = path.strip('/')
MinRK
reorganize who knows what about paths...
r15420 os_path = self._get_os_path(path=path)
Brian E. Granger
Small refactoring of is_hidden to take root as default kwarg.
r15108 return is_hidden(os_path, self.notebook_dir)
Brian E. Granger
Creating and testing IPython.html.utils.is_hidden.
r15097
MinRK
reorganize who knows what about paths...
r15420 def _get_os_path(self, name=None, path=''):
MinRK
move os_path to FileNBMan...
r13070 """Given a notebook name and a URL path, return its file system
path.
Parameters
----------
name : string
The name of a notebook file with the .ipynb extension
path : string
The relative URL path (with '/' as separator) to the named
notebook.
Returns
-------
path : string
A file system path that combines notebook_dir (location where
server started), the relative path, and the filename with the
current operating system's url.
"""
if name is not None:
MinRK
reorganize who knows what about paths...
r15420 path = path + '/' + name
return to_os_path(path, self.notebook_dir)
MinRK
move os_path to FileNBMan...
r13070
MinRK
adjust definition of 'path' in notebooks...
r13067 def notebook_exists(self, name, path=''):
Zachary Sailer
handle path separators with os.sep and add tests...
r13032 """Returns a True if the notebook exists. Else, returns False.
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046
Zachary Sailer
handle path separators with os.sep and add tests...
r13032 Parameters
----------
name : string
The name of the notebook you are checking.
path : string
The relative path to the notebook (with '/' as separator)
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046
Zachary Sailer
handle path separators with os.sep and add tests...
r13032 Returns
-------
bool
"""
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 path = path.strip('/')
MinRK
reorganize who knows what about paths...
r15420 nbpath = self._get_os_path(name, path=path)
MinRK
adjust definition of 'path' in notebooks...
r13067 return os.path.isfile(nbpath)
Zachary Sailer
manual rebase notebooks web services
r12984
Brian E. Granger
Get the existing tests working.
r15079 # TODO: Remove this after we create the contents web service and directories are
# no longer listed by the notebook web service.
Brian E. Granger
Server side logic for directories.
r15069 def list_dirs(self, path):
"""List the directories for a given API style path."""
path = path.strip('/')
MinRK
reorganize who knows what about paths...
r15420 os_path = self._get_os_path('', path)
Paul Ivanov
fix test suite...
r15630 if not os.path.isdir(os_path):
raise web.HTTPError(404, u'directory does not exist: %r' % os_path)
elif is_hidden(os_path, self.notebook_dir):
Paul Ivanov
log refusal to serve hidden files dirs
r15610 self.log.info("Refusing to serve hidden directory, via 404 Error")
Brian E. Granger
Creating and testing IPython.html.utils.is_hidden.
r15097 raise web.HTTPError(404, u'directory does not exist: %r' % os_path)
Brian E. Granger
Server side logic for directories.
r15069 dir_names = os.listdir(os_path)
dirs = []
for name in dir_names:
MinRK
reorganize who knows what about paths...
r15420 os_path = self._get_os_path(name, path)
Thomas Kluyver
Hide directories beginning with _ from the dashboard....
r15522 if os.path.isdir(os_path) and not is_hidden(os_path, self.notebook_dir)\
Thomas Kluyver
Make hidden directories configurable
r15525 and self.should_list(name):
Brian E. Granger
Addressing review comments....
r15093 try:
model = self.get_dir_model(name, path)
except IOError:
pass
Brian E. Granger
Server side logic for directories.
r15069 dirs.append(model)
Thomas Kluyver
Case insensitive sorting in the dashboard....
r15523 dirs = sorted(dirs, key=sort_key)
Brian E. Granger
Server side logic for directories.
r15069 return dirs
Brian E. Granger
Get the existing tests working.
r15079 # TODO: Remove this after we create the contents web service and directories are
# no longer listed by the notebook web service.
Brian E. Granger
Server side logic for directories.
r15069 def get_dir_model(self, name, path=''):
"""Get the directory model given a directory name and its API style path"""
path = path.strip('/')
MinRK
reorganize who knows what about paths...
r15420 os_path = self._get_os_path(name, path)
Brian E. Granger
Server side logic for directories.
r15069 if not os.path.isdir(os_path):
raise IOError('directory does not exist: %r' % os_path)
info = os.stat(os_path)
last_modified = tz.utcfromtimestamp(info.st_mtime)
created = tz.utcfromtimestamp(info.st_ctime)
# Create the notebook model.
model ={}
model['name'] = name
model['path'] = path
model['last_modified'] = last_modified
model['created'] = created
model['type'] = 'directory'
return model
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 def list_notebooks(self, path):
Zachary Sailer
Code review changes....
r13048 """Returns a list of dictionaries that are the standard model
for all notebooks in the relative 'path'.
Parameters
----------
path : str
the URL path that describes the relative path for the
listed notebooks
Returns
-------
notebooks : list of dicts
a list of the notebook models without 'content'
"""
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 path = path.strip('/')
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 notebook_names = self.get_notebook_names(path)
Thomas Kluyver
Make hidden directories configurable
r15525 notebooks = [self.get_notebook(name, path, content=False)
for name in notebook_names if self.should_list(name)]
Thomas Kluyver
Case insensitive sorting in the dashboard....
r15523 notebooks = sorted(notebooks, key=sort_key)
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 return notebooks
Konrad Hinsen
NotebookManager API: rename *notebook_model methods to *notebook
r15290 def get_notebook(self, name, path='', content=True):
Thomas Kluyver
Add HTTP handlers for nbconvert
r13827 """ Takes a path and name for a notebook and returns its model
Zachary Sailer
Code review changes....
r13048
Parameters
----------
name : str
the name of the notebook
path : str
the URL path that describes the relative path for
the notebook
Returns
-------
model : dict
the notebook model. If contents=True, returns the 'contents'
dict in the model as well.
"""
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 path = path.strip('/')
MinRK
fix dashboard upload
r13072 if not self.notebook_exists(name=name, path=path):
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 raise web.HTTPError(404, u'Notebook does not exist: %s' % name)
MinRK
reorganize who knows what about paths...
r15420 os_path = self._get_os_path(name, path)
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 info = os.stat(os_path)
MinRK
add timezone info to `last_modified` in notebook managers...
r11145 last_modified = tz.utcfromtimestamp(info.st_mtime)
MinRK
fix dashboard upload
r13072 created = tz.utcfromtimestamp(info.st_ctime)
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 # Create the notebook model.
model ={}
model['name'] = name
model['path'] = path
Brian E. Granger
Review and refactoring of notebooks web service.
r13051 model['last_modified'] = last_modified
MinRK
fix created timestamp in notebook model
r13143 model['created'] = created
Brian E. Granger
Addressing review comments....
r15093 model['type'] = 'notebook'
MinRK
sign notebooks
r14856 if content:
Thomas Kluyver
Specify encoding for loading and saving notebooks.
r13112 with io.open(os_path, 'r', encoding='utf-8') as f:
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 try:
Brian E. Granger
Review and refactoring of notebooks web service.
r13051 nb = current.read(f, u'json')
except Exception as e:
raise web.HTTPError(400, u"Unreadable Notebook: %s %s" % (os_path, e))
MinRK
Add Trust Notebook to File menu
r15655 self.mark_trusted_cells(nb, name, path)
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 model['content'] = nb
return model
Zachary Sailer
Add 'patch' to session & notebook, rename working
r12997
Konrad Hinsen
NotebookManager API: rename *notebook_model methods to *notebook
r15290 def save_notebook(self, model, name='', path=''):
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 """Save the notebook model and return the model with no content."""
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 path = path.strip('/')
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046
if 'content' not in model:
raise web.HTTPError(400, u'No notebook JSON data provided')
Brian E. Granger
Addressing review comments....
r15093
MinRK
notebooks should always have one checkpoint...
r13245 # One checkpoint should always exist
if self.notebook_exists(name, path) and not self.list_checkpoints(name, path):
self.create_checkpoint(name, path)
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046
MinRK
adjust definition of 'path' in notebooks...
r13067 new_path = model.get('path', path).strip('/')
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 new_name = model.get('name', name)
if path != new_path or name != new_name:
self.rename_notebook(name, path, new_name, new_path)
Brian E. Granger
When a notebook is written to file, name the metadata name u''.
r11052
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 # Save the notebook file
MinRK
reorganize who knows what about paths...
r15420 os_path = self._get_os_path(new_name, new_path)
Brian E. Granger
Review and refactoring of notebooks web service.
r13051 nb = current.to_notebook_json(model['content'])
MinRK
sign notebooks
r14856
MinRK
Add Trust Notebook to File menu
r15655 self.check_and_sign(nb, new_name, new_path)
MinRK
sign notebooks
r14856
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 if 'name' in nb['metadata']:
nb['metadata']['name'] = u''
Brian E. Granger
Massive work on the notebook document format....
r4484 try:
Brian E. Granger
Review and refactoring of notebooks web service.
r13051 self.log.debug("Autosaving notebook %s", os_path)
Thomas Kluyver
Specify encoding for loading and saving notebooks.
r13112 with io.open(os_path, 'w', encoding='utf-8') as f:
Brian E. Granger
Making JSON the default .ipynb format.
r4633 current.write(nb, f, u'json')
MinRK
include error in 'Unexpected error' message.
r5709 except Exception as e:
Brian E. Granger
Review and refactoring of notebooks web service.
r13051 raise web.HTTPError(400, u'Unexpected error while autosaving notebook: %s %s' % (os_path, e))
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 # Save .py script as well
MinRK
allow saving notebook.py next to notebook.ipynb...
r5653 if self.save_script:
Brian E. Granger
Review and refactoring of notebooks web service.
r13051 py_path = os.path.splitext(os_path)[0] + '.py'
self.log.debug("Writing script %s", py_path)
MinRK
allow saving notebook.py next to notebook.ipynb...
r5653 try:
Brian E. Granger
Review and refactoring of notebooks web service.
r13051 with io.open(py_path, 'w', encoding='utf-8') as f:
Thomas Kluyver
Pass nbformat object to write call to save .py script...
r13513 current.write(nb, f, u'py')
MinRK
include error in 'Unexpected error' message.
r5709 except Exception as e:
Brian E. Granger
Review and refactoring of notebooks web service.
r13051 raise web.HTTPError(400, u'Unexpected error while saving notebook as script: %s %s' % (py_path, e))
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046
Konrad Hinsen
NotebookManager API: rename *notebook_model methods to *notebook
r15290 model = self.get_notebook(new_name, new_path, content=False)
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 return model
Konrad Hinsen
NotebookManager API: rename *notebook_model methods to *notebook
r15290 def update_notebook(self, model, name, path=''):
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 """Update the notebook's path and/or name"""
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 path = path.strip('/')
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 new_name = model.get('name', name)
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 new_path = model.get('path', path).strip('/')
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 if path != new_path or name != new_name:
self.rename_notebook(name, path, new_name, new_path)
Konrad Hinsen
NotebookManager API: rename *notebook_model methods to *notebook
r15290 model = self.get_notebook(new_name, new_path, content=False)
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 return model
Konrad Hinsen
NotebookManager API: rename *notebook_model methods to *notebook
r15290 def delete_notebook(self, name, path=''):
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 """Delete notebook by name and path."""
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 path = path.strip('/')
MinRK
reorganize who knows what about paths...
r15420 os_path = self._get_os_path(name, path)
Brian E. Granger
Review and refactoring of notebooks web service.
r13051 if not os.path.isfile(os_path):
raise web.HTTPError(404, u'Notebook does not exist: %s' % os_path)
MinRK
add checkpoint API to FileNBManager
r10497
# clear checkpoints
Brian E. Granger
Review and refactoring of notebooks web service.
r13051 for checkpoint in self.list_checkpoints(name, path):
MinRK
use 'id' for checkpoint ID key...
r13122 checkpoint_id = checkpoint['id']
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
if os.path.isfile(cp_path):
self.log.debug("Unlinking checkpoint %s", cp_path)
os.unlink(cp_path)
MinRK
deleting a notebook deletes its checkpoints...
r10518
Zachary Sailer
add error catching to kernel manager...
r13052 self.log.debug("Unlinking notebook %s", os_path)
os.unlink(os_path)
Brian E. Granger
Massive work on the notebook document format....
r4484
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 def rename_notebook(self, old_name, old_path, new_name, new_path):
"""Rename a notebook."""
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 old_path = old_path.strip('/')
new_path = new_path.strip('/')
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 if new_name == old_name and new_path == old_path:
return
Brian Granger
Fixing docstring in the notebook manager.
r5877
MinRK
reorganize who knows what about paths...
r15420 new_os_path = self._get_os_path(new_name, new_path)
old_os_path = self._get_os_path(old_name, old_path)
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046
# Should we proceed with the move?
Brian E. Granger
Review and refactoring of notebooks web service.
r13051 if os.path.isfile(new_os_path):
Zachary Sailer
fixed notebook rename after nbmanager refactor
r13056 raise web.HTTPError(409, u'Notebook with name already exists: %s' % new_os_path)
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 if self.save_script:
Brian E. Granger
Review and refactoring of notebooks web service.
r13051 old_py_path = os.path.splitext(old_os_path)[0] + '.py'
new_py_path = os.path.splitext(new_os_path)[0] + '.py'
if os.path.isfile(new_py_path):
raise web.HTTPError(409, u'Python script with name already exists: %s' % new_py_path)
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046
# Move the notebook file
try:
Pankaj Pandey
FileNotebookManager: Use shutil.move() instead of os.rename()...
r16212 shutil.move(old_os_path, new_os_path)
Brian E. Granger
Review and refactoring of notebooks web service.
r13051 except Exception as e:
MinRK
fix dashboard upload
r13072 raise web.HTTPError(500, u'Unknown error renaming notebook: %s %s' % (old_os_path, e))
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046
# Move the checkpoints
old_checkpoints = self.list_checkpoints(old_name, old_path)
for cp in old_checkpoints:
MinRK
use 'id' for checkpoint ID key...
r13122 checkpoint_id = cp['id']
Zachary Sailer
fixed notebook rename after nbmanager refactor
r13056 old_cp_path = self.get_checkpoint_path(checkpoint_id, old_name, old_path)
new_cp_path = self.get_checkpoint_path(checkpoint_id, new_name, new_path)
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 if os.path.isfile(old_cp_path):
self.log.debug("Renaming checkpoint %s -> %s", old_cp_path, new_cp_path)
Pankaj Pandey
FileNotebookManager: Use shutil.move() instead of os.rename()...
r16212 shutil.move(old_cp_path, new_cp_path)
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046
# Move the .py script
if self.save_script:
Pankaj Pandey
FileNotebookManager: Use shutil.move() instead of os.rename()...
r16212 shutil.move(old_py_path, new_py_path)
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046
MinRK
add checkpoint API to FileNBManager
r10497 # Checkpoint-related utilities
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 def get_checkpoint_path(self, checkpoint_id, name, path=''):
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 """find the path to a checkpoint"""
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 path = path.strip('/')
MinRK
fix checkpoint filename
r13244 basename, _ = os.path.splitext(name)
MinRK
normalize unicode notebook filenames...
r10777 filename = u"{name}-{checkpoint_id}{ext}".format(
MinRK
fix checkpoint filename
r13244 name=basename,
MinRK
add checkpoint API to FileNBManager
r10497 checkpoint_id=checkpoint_id,
ext=self.filename_ext,
)
MinRK
create checkpoints dir in notebook subdirectories
r16447 os_path = self._get_os_path(path=path)
cp_dir = os.path.join(os_path, self.checkpoint_dir)
MinRK
add utils.path.ensure_dir_exists...
r16486 ensure_dir_exists(cp_dir)
MinRK
create checkpoints dir in notebook subdirectories
r16447 cp_path = os.path.join(cp_dir, filename)
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 return cp_path
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 def get_checkpoint_model(self, checkpoint_id, name, path=''):
MinRK
checkpoint info is a dict...
r10500 """construct the info dict for a given checkpoint"""
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 path = path.strip('/')
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
stats = os.stat(cp_path)
MinRK
add timezone info to `last_modified` in notebook managers...
r11145 last_modified = tz.utcfromtimestamp(stats.st_mtime)
MinRK
checkpoint info is a dict...
r10500 info = dict(
MinRK
use 'id' for checkpoint ID key...
r13122 id = checkpoint_id,
MinRK
checkpoint info is a dict...
r10500 last_modified = last_modified,
)
return info
MinRK
add checkpoint API to FileNBManager
r10497 # public checkpoint API
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 def create_checkpoint(self, name, path=''):
MinRK
add checkpoint API to FileNBManager
r10497 """Create a checkpoint from the current state of a notebook"""
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 path = path.strip('/')
MinRK
reorganize who knows what about paths...
r15420 nb_path = self._get_os_path(name, path)
MinRK
checkpoint info is a dict...
r10500 # only the one checkpoint ID:
MinRK
normalize unicode notebook filenames...
r10777 checkpoint_id = u"checkpoint"
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
self.log.debug("creating checkpoint for notebook %s", name)
MinRK
fallback on copy, copyfile if copy2 fails...
r15827 self._copy(nb_path, cp_path)
MinRK
checkpoint info is a dict...
r10500
# return the checkpoint info
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 return self.get_checkpoint_model(checkpoint_id, name, path)
MinRK
add checkpoint API to FileNBManager
r10497
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 def list_checkpoints(self, name, path=''):
MinRK
add checkpoint API to FileNBManager
r10497 """list the checkpoints for a given notebook
Paul Ivanov
print info string on interrupt, log it on startup
r10019
MinRK
add checkpoint API to FileNBManager
r10497 This notebook manager currently only supports one checkpoint per notebook.
"""
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 path = path.strip('/')
Zachary Sailer
manual rebase notebooks web services
r12984 checkpoint_id = "checkpoint"
MinRK
create checkpoints dir in notebook subdirectories
r16447 os_path = self.get_checkpoint_path(checkpoint_id, name, path)
if not os.path.exists(os_path):
MinRK
add checkpoint API to FileNBManager
r10497 return []
MinRK
checkpoint info is a dict...
r10500 else:
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 return [self.get_checkpoint_model(checkpoint_id, name, path)]
MinRK
checkpoint info is a dict...
r10500
MinRK
add checkpoint API to FileNBManager
r10497
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 def restore_checkpoint(self, checkpoint_id, name, path=''):
MinRK
add checkpoint API to FileNBManager
r10497 """restore a notebook to a checkpointed state"""
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 path = path.strip('/')
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 self.log.info("restoring Notebook %s from checkpoint %s", name, checkpoint_id)
MinRK
reorganize who knows what about paths...
r15420 nb_path = self._get_os_path(name, path)
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
MinRK
add checkpoint API to FileNBManager
r10497 if not os.path.isfile(cp_path):
MinRK
checkpoint info is a dict...
r10500 self.log.debug("checkpoint file does not exist: %s", cp_path)
MinRK
add checkpoint API to FileNBManager
r10497 raise web.HTTPError(404,
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 u'Notebook checkpoint does not exist: %s-%s' % (name, checkpoint_id)
MinRK
add checkpoint API to FileNBManager
r10497 )
# ensure notebook is readable (never restore from an unreadable notebook)
Thomas Kluyver
Specify encoding for loading and saving notebooks.
r13112 with io.open(cp_path, 'r', encoding='utf-8') as f:
Thomas Kluyver
Fix a couple of static analysis warnings
r15526 current.read(f, u'json')
MinRK
fallback on copy, copyfile if copy2 fails...
r15827 self._copy(cp_path, nb_path)
MinRK
add checkpoint API to FileNBManager
r10497 self.log.debug("copying %s -> %s", cp_path, nb_path)
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 def delete_checkpoint(self, checkpoint_id, name, path=''):
MinRK
add checkpoint API to FileNBManager
r10497 """delete a notebook's checkpoint"""
MinRK
ensure 'path' never has leading or trailing slash in nbmanager...
r13078 path = path.strip('/')
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 cp_path = self.get_checkpoint_path(checkpoint_id, name, path)
if not os.path.isfile(cp_path):
MinRK
add checkpoint API to FileNBManager
r10497 raise web.HTTPError(404,
Brian E. Granger
Review and refactoring of notebooks web service.
r13051 u'Notebook checkpoint does not exist: %s%s-%s' % (path, name, checkpoint_id)
MinRK
add checkpoint API to FileNBManager
r10497 )
Zachary Sailer
refactoring of nbmanager and filenbmanager...
r13046 self.log.debug("unlinking %s", cp_path)
os.unlink(cp_path)
MinRK
add checkpoint API to FileNBManager
r10497
Paul Ivanov
print info string on interrupt, log it on startup
r10019 def info_string(self):
return "Serving notebooks from local directory: %s" % self.notebook_dir
Dale Jung
API: Allow NotebookManagers to control kernel startup dir. #5468
r16052
def get_kernel_path(self, name, path='', model=None):
""" Return the path to start kernel in """
return os.path.join(self.notebook_dir, path)