##// END OF EJS Templates
review fixes on tests, add extra kernel api test
review fixes on tests, add extra kernel api test

File last commit:

r13045:cc15133f
r13045:cc15133f
Show More
filenbmanager.py
347 lines | 14.2 KiB | text/x-python | PythonLexer
Brian E. Granger
More review changes....
r4609 """A notebook manager that uses the local file system for storage.
Authors:
* Brian Granger
"""
Brian E. Granger
Massive work on the notebook document format....
r4484 #-----------------------------------------------------------------------------
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 # Copyright (C) 2011 The IPython Development Team
Brian E. Granger
Massive work on the notebook document format....
r4484 #
# Distributed under the terms of the BSD License. The full license is in
Brian E. Granger
More review changes....
r4609 # the file COPYING, distributed as part of this software.
Brian E. Granger
Massive work on the notebook document format....
r4484 #-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import datetime
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
MinRK
normalize unicode notebook filenames...
r10777 from unicodedata import normalize
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
Brian E. Granger
Massive work on the notebook document format....
r4484 from IPython.nbformat import current
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 from IPython.utils.traitlets import Unicode, Dict, Bool, TraitError
MinRK
add timezone info to `last_modified` in notebook managers...
r11145 from IPython.utils import tz
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
add checkpoint API to FileNBManager
r10497 checkpoint_dir = Unicode(config=True,
help="""The location in which to keep notebook checkpoints
By default, it is notebook-dir/.ipynb_checkpoints
"""
)
def _checkpoint_dir_default(self):
return os.path.join(self.notebook_dir, '.ipynb_checkpoints')
def _checkpoint_dir_changed(self, name, old, new):
"""do a bit of validation of the checkpoint dir"""
if not os.path.isabs(new):
# If we receive a non-absolute path, make it absolute.
abs_new = os.path.abspath(new)
self.checkpoint_dir = abs_new
return
if os.path.exists(new) and not os.path.isdir(new):
raise TraitError("checkpoint dir %r is not a directory" % new)
if not os.path.exists(new):
self.log.info("Creating checkpoint dir %s", new)
try:
os.mkdir(new)
except:
raise TraitError("Couldn't create checkpoint dir %r" % new)
Brian E. Granger
Massive work on the notebook document format....
r4484 filename_ext = Unicode(u'.ipynb')
MinRK
add checkpoint API to FileNBManager
r10497
Zachary Sailer
manual rebase notebooks web services
r12984 def get_notebook_names(self, path):
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 """List all notebook names in the notebook dir."""
Zachary Sailer
fixing broken links from recent changes....
r13033 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
manual rebase notebooks web services
r12984
def list_notebooks(self, path):
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 """List all notebooks in the notebook dir."""
Zachary Sailer
Add 'patch' to session & notebook, rename working
r12997 notebook_names = self.get_notebook_names(path)
Zachary Sailer
url encode/decode tests added to nbmanager
r13031 notebooks = []
Zachary Sailer
Add 'patch' to session & notebook, rename working
r12997 for name in notebook_names:
Zachary Sailer
standard model changes
r13011 model = self.notebook_model(name, path, content=False)
Zachary Sailer
url encode/decode tests added to nbmanager
r13031 notebooks.append(model)
return notebooks
Zachary Sailer
Add 'patch' to session & notebook, rename working
r12997
Zachary Sailer
review fixes on tests, add extra kernel api test
r13045 def update_notebook(self, data, notebook_name, notebook_path='/'):
Zachary Sailer
Add 'patch' to session & notebook, rename working
r12997 """Changes notebook"""
changes = data.keys()
for change in changes:
Zachary Sailer
handle path separators with os.sep and add tests...
r13032 full_path = self.get_os_path(notebook_name, notebook_path)
Zachary Sailer
Renaming fixed
r13018 if change == "name":
Zachary Sailer
handle path separators with os.sep and add tests...
r13032 new_path = self.get_os_path(data['name'], notebook_path)
Zachary Sailer
add tests for session api
r13044 if not os.path.isfile(new_path):
Zachary Sailer
Renaming fixed
r13018 os.rename(full_path,
Zachary Sailer
handle path separators with os.sep and add tests...
r13032 self.get_os_path(data['name'], notebook_path))
Zachary Sailer
Renaming fixed
r13018 notebook_name = data['name']
Zachary Sailer
add tests for session api
r13044 else:
Zachary Sailer
Added notebooks API tests.
r13041 raise web.HTTPError(409, u'Notebook name already exists.')
Zachary Sailer
Renaming fixed
r13018 if change == "path":
Zachary Sailer
handle path separators with os.sep and add tests...
r13032 new_path = self.get_os_path(data['name'], data['path'])
Zachary Sailer
allow rename in subdirectory notebooks
r12998 stutil.move(full_path, new_path)
Zachary Sailer
Renaming fixed
r13018 notebook_path = data['path']
Zachary Sailer
Add 'patch' to session & notebook, rename working
r12997 if change == "content":
self.save_notebook(data, notebook_name, notebook_path)
model = self.notebook_model(notebook_name, notebook_path)
Zachary Sailer
Added notebooks API tests.
r13041 return model
Brian E. Granger
Massive work on the notebook document format....
r4484
Zachary Sailer
handle path separators with os.sep and add tests...
r13032 def notebook_exists(self, name, path):
"""Returns a True if the notebook exists. Else, returns False.
Parameters
----------
name : string
The name of the notebook you are checking.
path : string
The relative path to the notebook (with '/' as separator)
Returns
-------
bool
"""
path = self.get_os_path(name, path)
return os.path.isfile(path)
Zachary Sailer
manual rebase notebooks web services
r12984
MinRK
add checkpoint API to FileNBManager
r10497 def read_notebook_object_from_path(self, path):
"""read a notebook object from a path"""
Brian E. Granger
Massive work on the notebook document format....
r4484 info = os.stat(path)
MinRK
add timezone info to `last_modified` in notebook managers...
r11145 last_modified = tz.utcfromtimestamp(info.st_mtime)
Brian E. Granger
Making JSON the default .ipynb format.
r4633 with open(path,'r') as f:
s = f.read()
try:
# v1 and v2 and json in the .ipynb files.
nb = current.reads(s, u'json')
MinRK
better message when notebook format is not supported...
r11643 except ValueError as e:
msg = u"Unreadable Notebook: %s" % e
raise web.HTTPError(400, msg, reason=msg)
MinRK
add checkpoint API to FileNBManager
r10497 return last_modified, nb
Zachary Sailer
fix bug in test_contentmanager
r13039 def read_notebook_object(self, notebook_name, notebook_path='/'):
Zachary Sailer
manual rebase notebooks web services
r12984 """Get the Notebook representation of a notebook by notebook_name."""
Zachary Sailer
handle path separators with os.sep and add tests...
r13032 path = self.get_os_path(notebook_name, notebook_path)
MinRK
add checkpoint API to FileNBManager
r10497 if not os.path.isfile(path):
Zachary Sailer
manual rebase notebooks web services
r12984 raise web.HTTPError(404, u'Notebook does not exist: %s' % notebook_name)
MinRK
add checkpoint API to FileNBManager
r10497 last_modified, nb = self.read_notebook_object_from_path(path)
Brian Granger
Always use filename as the notebook name.
r7231 # Always use the filename as the notebook name.
Brian E. Granger
When a notebook is written to file, name the metadata name u''.
r11052 # Eventually we will get rid of the notebook name in the metadata
# but for now, that name is just an empty string. Until the notebooks
# web service knows about names in URLs we still pass the name
# back to the web app using the metadata though.
Kent Inverarity
change to minrk's suggestion from mailing list
r7615 nb.metadata.name = os.path.splitext(os.path.basename(path))[0]
Brian E. Granger
Massive work on the notebook document format....
r4484 return last_modified, nb
MinRK
add checkpoint API to FileNBManager
r10497
Zachary Sailer
fix bug in test_contentmanager
r13039 def write_notebook_object(self, nb, notebook_name=None, notebook_path='/', new_name= None):
Zachary Sailer
manual rebase notebooks web services
r12984 """Save an existing notebook object by notebook_name."""
Zachary Sailer
Add 'patch' to session & notebook, rename working
r12997 if new_name == None:
try:
new_name = normalize('NFC', nb.metadata.name)
except AttributeError:
raise web.HTTPError(400, u'Missing notebook name')
Zachary Sailer
manual rebase notebooks web services
r12984 new_path = notebook_path
old_name = notebook_name
old_checkpoints = self.list_checkpoints(old_name)
Zachary Sailer
handle path separators with os.sep and add tests...
r13032 path = self.get_os_path(new_name, new_path)
Zachary Sailer
manual rebase notebooks web services
r12984
Brian E. Granger
When a notebook is written to file, name the metadata name u''.
r11052 # Right before we save the notebook, we write an empty string as the
# notebook name in the metadata. This is to prepare for removing
# this attribute entirely post 1.0. The web app still uses the metadata
# name for now.
nb.metadata.name = u''
Brian E. Granger
Massive work on the notebook document format....
r4484 try:
MinRK
deleting a notebook deletes its checkpoints...
r10518 self.log.debug("Autosaving notebook %s", path)
Brian E. Granger
Massive work on the notebook document format....
r4484 with open(path,'w') 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:
MinRK
deleting a notebook deletes its checkpoints...
r10518 raise web.HTTPError(400, u'Unexpected error while autosaving notebook: %s' % e)
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180
MinRK
allow saving notebook.py next to notebook.ipynb...
r5653 # save .py script as well
if self.save_script:
pypath = os.path.splitext(path)[0] + '.py'
MinRK
add checkpoint API to FileNBManager
r10497 self.log.debug("Writing script %s", pypath)
MinRK
allow saving notebook.py next to notebook.ipynb...
r5653 try:
Thomas Kluyver
Specify UTF-8 encoding for saving notebook as script.
r6031 with io.open(pypath,'w', encoding='utf-8') as f:
MinRK
allow saving notebook.py next to notebook.ipynb...
r5653 current.write(nb, f, u'py')
MinRK
include error in 'Unexpected error' message.
r5709 except Exception as e:
raise web.HTTPError(400, u'Unexpected error while saving notebook as script: %s' % e)
MinRK
allow saving notebook.py next to notebook.ipynb...
r5653
Zachary Sailer
manual rebase notebooks web services
r12984 if old_name != None:
# remove old files if the name changed
if old_name != new_name:
# remove renamed original, if it exists
Zachary Sailer
handle path separators with os.sep and add tests...
r13032 old_path = self.get_os_path(old_name, notebook_path)
Zachary Sailer
manual rebase notebooks web services
r12984 if os.path.isfile(old_path):
self.log.debug("unlinking notebook %s", old_path)
os.unlink(old_path)
MinRK
add checkpoint API to FileNBManager
r10497
Zachary Sailer
manual rebase notebooks web services
r12984 # cleanup old script, if it exists
if self.save_script:
old_pypath = os.path.splitext(old_path)[0] + '.py'
if os.path.isfile(old_pypath):
self.log.debug("unlinking script %s", old_pypath)
os.unlink(old_pypath)
# rename checkpoints to follow file
for cp in old_checkpoints:
checkpoint_id = cp['checkpoint_id']
old_cp_path = self.get_checkpoint_path_by_name(old_name, checkpoint_id)
new_cp_path = self.get_checkpoint_path_by_name(new_name, checkpoint_id)
if os.path.isfile(old_cp_path):
self.log.debug("renaming checkpoint %s -> %s", old_cp_path, new_cp_path)
os.rename(old_cp_path, new_cp_path)
MinRK
add checkpoint API to FileNBManager
r10497
Zachary Sailer
manual rebase notebooks web services
r12984 return new_name
MinRK
add checkpoint API to FileNBManager
r10497
Zachary Sailer
manual rebase notebooks web services
r12984 def delete_notebook(self, notebook_name, notebook_path):
"""Delete notebook by notebook_name."""
Zachary Sailer
handle path separators with os.sep and add tests...
r13032 nb_path = self.get_os_path(notebook_name, notebook_path)
MinRK
deleting a notebook deletes its checkpoints...
r10518 if not os.path.isfile(nb_path):
Zachary Sailer
manual rebase notebooks web services
r12984 raise web.HTTPError(404, u'Notebook does not exist: %s' % notebook_name)
MinRK
add checkpoint API to FileNBManager
r10497
# clear checkpoints
Zachary Sailer
manual rebase notebooks web services
r12984 for checkpoint in self.list_checkpoints(notebook_name):
MinRK
deleting a notebook deletes its checkpoints...
r10518 checkpoint_id = checkpoint['checkpoint_id']
Zachary Sailer
manual rebase notebooks web services
r12984 path = self.get_checkpoint_path(notebook_name, checkpoint_id)
MinRK
deleting a notebook deletes its checkpoints...
r10518 self.log.debug(path)
MinRK
add checkpoint API to FileNBManager
r10497 if os.path.isfile(path):
MinRK
deleting a notebook deletes its checkpoints...
r10518 self.log.debug("unlinking checkpoint %s", path)
MinRK
add checkpoint API to FileNBManager
r10497 os.unlink(path)
MinRK
deleting a notebook deletes its checkpoints...
r10518
self.log.debug("unlinking notebook %s", nb_path)
os.unlink(nb_path)
Brian E. Granger
Massive work on the notebook document format....
r4484
Zachary Sailer
fix bug in test_contentmanager
r13039 def increment_filename(self, basename, notebook_path='/'):
Brian Granger
Fixing docstring in the notebook manager.
r5877 """Return a non-used filename of the form basename<int>.
This searches through the filenames (basename0, basename1, ...)
until is find one that is not already being used. It is used to
create Untitled and Copy names that are unique.
"""
Brian E. Granger
Massive work on the notebook document format....
r4484 i = 0
while True:
Zachary Sailer
manual rebase notebooks web services
r12984 name = u'%s%i.ipynb' % (basename,i)
Zachary Sailer
handle path separators with os.sep and add tests...
r13032 path = self.get_os_path(name, notebook_path)
Brian E. Granger
Massive work on the notebook document format....
r4484 if not os.path.isfile(path):
break
else:
i = i+1
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 return name
MinRK
add checkpoint API to FileNBManager
r10497
# Checkpoint-related utilities
Zachary Sailer
fix bug in test_contentmanager
r13039 def get_checkpoint_path_by_name(self, name, checkpoint_id, notebook_path='/'):
MinRK
add checkpoint API to FileNBManager
r10497 """Return a full path to a notebook checkpoint, given its name and checkpoint id."""
MinRK
normalize unicode notebook filenames...
r10777 filename = u"{name}-{checkpoint_id}{ext}".format(
MinRK
add checkpoint API to FileNBManager
r10497 name=name,
checkpoint_id=checkpoint_id,
ext=self.filename_ext,
)
Zachary Sailer
manual rebase notebooks web services
r12984 if notebook_path ==None:
path = os.path.join(self.checkpoint_dir, filename)
else:
path = os.path.join(notebook_path, self.checkpoint_dir, filename)
MinRK
add checkpoint API to FileNBManager
r10497 return path
Zachary Sailer
fix bug in test_contentmanager
r13039 def get_checkpoint_path(self, notebook_name, checkpoint_id, notebook_path='/'):
MinRK
add checkpoint API to FileNBManager
r10497 """find the path to a checkpoint"""
Zachary Sailer
manual rebase notebooks web services
r12984 name = notebook_name
return self.get_checkpoint_path_by_name(name, checkpoint_id, notebook_path)
MinRK
add checkpoint API to FileNBManager
r10497
Zachary Sailer
fix bug in test_contentmanager
r13039 def get_checkpoint_info(self, notebook_name, checkpoint_id, notebook_path='/'):
MinRK
checkpoint info is a dict...
r10500 """construct the info dict for a given checkpoint"""
Zachary Sailer
manual rebase notebooks web services
r12984 path = self.get_checkpoint_path(notebook_name, checkpoint_id, notebook_path)
MinRK
checkpoint info is a dict...
r10500 stats = os.stat(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(
checkpoint_id = checkpoint_id,
last_modified = last_modified,
)
return info
MinRK
add checkpoint API to FileNBManager
r10497 # public checkpoint API
Zachary Sailer
fix bug in test_contentmanager
r13039 def create_checkpoint(self, notebook_name, notebook_path='/'):
MinRK
add checkpoint API to FileNBManager
r10497 """Create a checkpoint from the current state of a notebook"""
Zachary Sailer
handle path separators with os.sep and add tests...
r13032 nb_path = self.get_os_path(notebook_name, notebook_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
manual rebase notebooks web services
r12984 cp_path = self.get_checkpoint_path(notebook_name, checkpoint_id, notebook_path)
self.log.debug("creating checkpoint for notebook %s", notebook_name)
MinRK
add checkpoint API to FileNBManager
r10497 if not os.path.exists(self.checkpoint_dir):
os.mkdir(self.checkpoint_dir)
shutil.copy2(nb_path, cp_path)
MinRK
checkpoint info is a dict...
r10500
# return the checkpoint info
Zachary Sailer
manual rebase notebooks web services
r12984 return self.get_checkpoint_info(notebook_name, checkpoint_id, notebook_path)
MinRK
add checkpoint API to FileNBManager
r10497
Zachary Sailer
fix bug in test_contentmanager
r13039 def list_checkpoints(self, notebook_name, notebook_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.
"""
Zachary Sailer
manual rebase notebooks web services
r12984 checkpoint_id = "checkpoint"
path = self.get_checkpoint_path(notebook_name, checkpoint_id, notebook_path)
MinRK
checkpoint info is a dict...
r10500 if not os.path.exists(path):
MinRK
add checkpoint API to FileNBManager
r10497 return []
MinRK
checkpoint info is a dict...
r10500 else:
Zachary Sailer
manual rebase notebooks web services
r12984 return [self.get_checkpoint_info(notebook_name, checkpoint_id, notebook_path)]
MinRK
checkpoint info is a dict...
r10500
MinRK
add checkpoint API to FileNBManager
r10497
Zachary Sailer
fix bug in test_contentmanager
r13039 def restore_checkpoint(self, notebook_name, checkpoint_id, notebook_path='/'):
MinRK
add checkpoint API to FileNBManager
r10497 """restore a notebook to a checkpointed state"""
Zachary Sailer
manual rebase notebooks web services
r12984 self.log.info("restoring Notebook %s from checkpoint %s", notebook_name, checkpoint_id)
Zachary Sailer
handle path separators with os.sep and add tests...
r13032 nb_path = self.get_os_path(notebook_name, notebook_path)
Zachary Sailer
manual rebase notebooks web services
r12984 cp_path = self.get_checkpoint_path(notebook_name, checkpoint_id, notebook_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
manual rebase notebooks web services
r12984 u'Notebook checkpoint does not exist: %s-%s' % (notebook_name, checkpoint_id)
MinRK
add checkpoint API to FileNBManager
r10497 )
# ensure notebook is readable (never restore from an unreadable notebook)
last_modified, nb = self.read_notebook_object_from_path(cp_path)
shutil.copy2(cp_path, nb_path)
self.log.debug("copying %s -> %s", cp_path, nb_path)
Zachary Sailer
fix bug in test_contentmanager
r13039 def delete_checkpoint(self, notebook_name, checkpoint_id, notebook_path='/'):
MinRK
add checkpoint API to FileNBManager
r10497 """delete a notebook's checkpoint"""
Zachary Sailer
manual rebase notebooks web services
r12984 path = self.get_checkpoint_path(notebook_name, checkpoint_id, notebook_path)
MinRK
add checkpoint API to FileNBManager
r10497 if not os.path.isfile(path):
raise web.HTTPError(404,
Zachary Sailer
manual rebase notebooks web services
r12984 u'Notebook checkpoint does not exist: %s-%s' % (notebook_name, checkpoint_id)
MinRK
add checkpoint API to FileNBManager
r10497 )
self.log.debug("unlinking %s", path)
os.unlink(path)
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