##// 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
nbmanager.py
301 lines | 11.2 KiB | text/x-python | PythonLexer
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 """A base class notebook manager.
Authors:
* Brian Granger
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
Brian Granger
Fixing minor things for the Azure backed nb storage.
r8181 import os
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 import uuid
from tornado import web
Zachary Sailer
allow spaces in notebook path
r13012 from urllib import quote, unquote
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180
from IPython.config.configurable import LoggingConfigurable
from IPython.nbformat import current
Brian Granger
Fixing minor things for the Azure backed nb storage.
r8181 from IPython.utils.traitlets import List, Dict, Unicode, TraitError
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
Brian Granger
Renaming BaseNotebookManager->NotebookManager to preserve config.
r8194 class NotebookManager(LoggingConfigurable):
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180
Brian Granger
Fixing minor things for the Azure backed nb storage.
r8181 # Todo:
# The notebook_dir attribute is used to mean a couple of different things:
# 1. Where the notebooks are stored if FileNotebookManager is used.
# 2. The cwd of the kernel for a project.
# Right now we use this attribute in a number of different places and
MinRK
add checkpoint API to FileNBManager
r10497 # we are going to have to disentangle all of this.
Brian Granger
Fixing minor things for the Azure backed nb storage.
r8181 notebook_dir = Unicode(os.getcwdu(), config=True, help="""
Zachary Sailer
manual rebase notebooks web services
r12984 The directory to use for notebooks.
""")
Paul Ivanov
cleaning up named_notebook_path
r13026
Zachary Sailer
manual rebase notebooks web services
r12984 def named_notebook_path(self, notebook_path):
Paul Ivanov
cleaning up named_notebook_path
r13026 """Given a notebook_path name, returns a (name, path) tuple, where
Paul Ivanov
more named_notebook_path cleanup...
r13028 name is a .ipynb file, and path is the directory for the file, which
*always* starts *and* ends with a '/' character.
Paul Ivanov
cleaning up named_notebook_path
r13026
Parameters
----------
notebook_path : string
A path that may be a .ipynb name or a directory
Returns
-------
name : string or None
Paul Ivanov
simplified named_notebook_path implementation...
r13027 the filename of the notebook, or None if not a .ipynb extension
path : string
Paul Ivanov
cleaning up named_notebook_path
r13026 the path to the directory which contains the notebook
"""
Zachary Sailer
manual rebase notebooks web services
r12984 names = notebook_path.split('/')
Paul Ivanov
more named_notebook_path cleanup...
r13028 names = [n for n in names if n != ''] # remove duplicate splits
Paul Ivanov
simplified named_notebook_path implementation...
r13027
Paul Ivanov
more named_notebook_path cleanup...
r13028 names = [''] + names
if names and names[-1].endswith(".ipynb"):
name = names[-1]
Paul Ivanov
simplified named_notebook_path implementation...
r13027 path = "/".join(names[:-1]) + '/'
Zachary Sailer
manual rebase notebooks web services
r12984 else:
Paul Ivanov
simplified named_notebook_path implementation...
r13027 name = None
path = "/".join(names) + '/'
Zachary Sailer
manual rebase notebooks web services
r12984 return name, path
Zachary Sailer
Added notebooks API tests.
r13041
def get_os_path(self, fname=None, path='/'):
"""Given a notebook name and a server URL path, return its file system
path.
Parameters
----------
fname : 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.
"""
parts = path.split('/')
parts = [p for p in parts if p != ''] # remove duplicate splits
if fname is not None:
parts += [fname]
path = os.path.join(self.notebook_dir, *parts)
return path
Paul Ivanov
simplified named_notebook_path implementation...
r13027
Zachary Sailer
allow spaces in notebook path
r13012 def url_encode(self, path):
Zachary Sailer
cleaning nb handlers, adding doc-strings/comments
r13036 """Returns the path with all special characters URL encoded"""
Zachary Sailer
url encode/decode tests added to nbmanager
r13031 parts = os.path.split(path)
Thomas Kluyver
Simplify encoding/decoding URL parts
r13021 return os.path.join(*[quote(p) for p in parts])
Zachary Sailer
allow spaces in notebook path
r13012
def url_decode(self, path):
Zachary Sailer
cleaning nb handlers, adding doc-strings/comments
r13036 """Returns the URL with special characters decoded"""
Zachary Sailer
url encode/decode tests added to nbmanager
r13031 parts = os.path.split(path)
Thomas Kluyver
Simplify encoding/decoding URL parts
r13021 return os.path.join(*[unquote(p) for p in parts])
Zachary Sailer
allow spaces in notebook path
r13012
Zachary Sailer
manual rebase notebooks web services
r12984 def _notebook_dir_changed(self, new):
Brian Granger
Fixing minor things for the Azure backed nb storage.
r8181 """do a bit of validation of the notebook dir"""
Ohad Ravid
Answer Issue #2366...
r8453 if not os.path.isabs(new):
# If we receive a non-absolute path, make it absolute.
abs_new = os.path.abspath(new)
Zachary Sailer
manual rebase notebooks web services
r12984 #self.notebook_dir = os.path.dirname(abs_new)
Ohad Ravid
Answer Issue #2366...
r8453 return
Brian Granger
Fixing minor things for the Azure backed nb storage.
r8181 if os.path.exists(new) and not os.path.isdir(new):
raise TraitError("notebook dir %r is not a directory" % new)
if not os.path.exists(new):
self.log.info("Creating notebook dir %s", new)
try:
os.mkdir(new)
except:
raise TraitError("Couldn't create notebook dir %r" % new)
Zachary Sailer
manual rebase notebooks web services
r12984
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 allowed_formats = List([u'json',u'py'])
Zachary Sailer
added folder creation ability using '/-new'
r13003 def add_new_folder(self, path=None):
new_path = os.path.join(self.notebook_dir, path)
if not os.path.exists(new_path):
os.makedirs(new_path)
else:
raise web.HTTPError(409, u'Directory already exists or creation permission not allowed.')
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180
Zachary Sailer
manual rebase notebooks web services
r12984 def load_notebook_names(self, path):
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 """Load the notebook names into memory.
This should be called once immediately after the notebook manager
is created to load the existing notebooks into the mapping in
memory.
"""
Zachary Sailer
manual rebase notebooks web services
r12984 self.list_notebooks(path)
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180
def list_notebooks(self):
"""List all notebooks.
This returns a list of dicts, each of the form::
dict(notebook_id=notebook,name=name)
This list of dicts should be sorted by name::
data = sorted(data, key=lambda item: item['name'])
"""
raise NotImplementedError('must be implemented in a subclass')
Zachary Sailer
review fixes on tests, add extra kernel api test
r13045 def notebook_model(self, name, path='/', content=True):
Zachary Sailer
manual rebase notebooks web services
r12984 """ Creates the standard notebook model """
Zachary Sailer
review fixes on tests, add extra kernel api test
r13045 last_modified, contents = self.read_notebook_model(name, path)
model = {"name": name,
"path": path,
"last_modified": last_modified.ctime()}
Zachary Sailer
Added notebooks API tests.
r13041 if content is True:
Zachary Sailer
standard model changes
r13011 model['content'] = contents
Zachary Sailer
manual rebase notebooks web services
r12984 return model
Zachary Sailer
fix bug in test_contentmanager
r13039 def get_notebook(self, notebook_name, notebook_path='/', format=u'json'):
Zachary Sailer
manual rebase notebooks web services
r12984 """Get the representation of a notebook in format by notebook_name."""
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 format = unicode(format)
if format not in self.allowed_formats:
raise web.HTTPError(415, u'Invalid notebook format: %s' % format)
kwargs = {}
Zachary Sailer
Download '.py' fixed, deleted debugging output
r13000 last_mod, nb = self.read_notebook_object(notebook_name, notebook_path)
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 if format == 'json':
# don't split lines for sending over the wire, because it
# should match the Python in-memory format.
kwargs['split_lines'] = False
Zachary Sailer
Download '.py' fixed, deleted debugging output
r13000 representation = current.writes(nb, format, **kwargs)
name = nb.metadata.get('name', 'notebook')
return last_mod, representation, name
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180
Zachary Sailer
review fixes on tests, add extra kernel api test
r13045 def read_notebook_model(self, notebook_name, notebook_path='/'):
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 """Get the object representation of a notebook by notebook_id."""
raise NotImplementedError('must be implemented in a subclass')
Zachary Sailer
review fixes on tests, add extra kernel api test
r13045 def save_notebook(self, model, name=None, path='/'):
"""Save the Notebook"""
if name is None:
name = self.increment_filename('Untitled', path)
if 'content' not in model:
metadata = current.new_metadata(name=name)
nb = current.new_notebook(metadata=metadata)
else:
nb = model['content']
self.write_notebook_object()
Zachary Sailer
fix bug in test_contentmanager
r13039 def save_new_notebook(self, data, notebook_path='/', name=None, format=u'json'):
Zachary Sailer
standard model changes
r13011 """Save a new notebook and return its name.
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180
If a name is passed in, it overrides any values in the notebook data
and the value in the data is updated to use that value.
"""
if format not in self.allowed_formats:
raise web.HTTPError(415, u'Invalid notebook format: %s' % format)
try:
nb = current.reads(data.decode('utf-8'), format)
except:
raise web.HTTPError(400, u'Invalid JSON data')
if name is None:
Zachary Sailer
Add 'patch' to session & notebook, rename working
r12997 try:
name = nb.metadata.name
except AttributeError:
raise web.HTTPError(400, u'Missing notebook name')
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 nb.metadata.name = name
Zachary Sailer
manual rebase notebooks web services
r12984 notebook_name = self.write_notebook_object(nb, notebook_path=notebook_path)
return notebook_name
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180
Zachary Sailer
review fixes on tests, add extra kernel api test
r13045 def save_notebook(self, data, notebook_path='/', name=None, format=u'json'):
Zachary Sailer
Add 'patch' to session & notebook, rename working
r12997 """Save an existing notebook by notebook_name."""
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 if format not in self.allowed_formats:
raise web.HTTPError(415, u'Invalid notebook format: %s' % format)
try:
nb = current.reads(data.decode('utf-8'), format)
except:
raise web.HTTPError(400, u'Invalid JSON data')
if name is not None:
nb.metadata.name = name
Zachary Sailer
Add 'patch' to session & notebook, rename working
r12997 self.write_notebook_object(nb, name, notebook_path, new_name)
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180
Zachary Sailer
review fixes on tests, add extra kernel api test
r13045 def write_notebook_model(self, model):
Zachary Sailer
manual rebase notebooks web services
r12984 """Write a notebook object and return its notebook_name.
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180
Zachary Sailer
manual rebase notebooks web services
r12984 If notebook_name is None, this method should create a new notebook_name.
If notebook_name is not None, this method should check to make sure it
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 exists and is valid.
"""
raise NotImplementedError('must be implemented in a subclass')
Zachary Sailer
manual rebase notebooks web services
r12984 def delete_notebook(self, notebook_name, notebook_path):
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 """Delete notebook by notebook_id."""
raise NotImplementedError('must be implemented in a subclass')
def increment_filename(self, name):
"""Increment a filename to make it unique.
This exists for notebook stores that must have unique names. When a notebook
is created or copied this method constructs a unique filename, typically
by appending an integer to the name.
"""
return name
Zachary Sailer
cleaning nb handlers, adding doc-strings/comments
r13036 def new_notebook(self, notebook_path='/'):
Thomas Kluyver
Update docstring
r13022 """Create a new notebook and return its notebook_name."""
Zachary Sailer
manual rebase notebooks web services
r12984 name = self.increment_filename('Untitled', notebook_path)
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 metadata = current.new_metadata(name=name)
nb = current.new_notebook(metadata=metadata)
Zachary Sailer
manual rebase notebooks web services
r12984 notebook_name = self.write_notebook_object(nb, notebook_path=notebook_path)
return notebook_name
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180
Zachary Sailer
fix bug in test_contentmanager
r13039 def copy_notebook(self, name, path='/'):
Thomas Kluyver
Update docstring
r13022 """Copy an existing notebook and return its new notebook_name."""
Zachary Sailer
manual rebase notebooks web services
r12984 last_mod, nb = self.read_notebook_object(name, path)
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 name = nb.metadata.name + '-Copy'
Zachary Sailer
manual rebase notebooks web services
r12984 name = self.increment_filename(name, path)
Brian Granger
Refactoring notebook managers and adding Azure backed storage....
r8180 nb.metadata.name = name
Zachary Sailer
manual rebase notebooks web services
r12984 notebook_name = self.write_notebook_object(nb, notebook_path = path)
return notebook_name
MinRK
add checkpoint API to FileNBManager
r10497
# Checkpoint-related
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 of the current state of a notebook
Returns a checkpoint_id for the new checkpoint.
"""
raise NotImplementedError("must be implemented in a subclass")
Zachary Sailer
fix bug in test_contentmanager
r13039 def list_checkpoints(self, notebook_name, notebook_path='/'):
MinRK
add checkpoint API to FileNBManager
r10497 """Return a list of checkpoints for a given notebook"""
return []
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 from one of its checkpoints"""
raise NotImplementedError("must be implemented in a subclass")
Brian Granger
Fixing minor things for the Azure backed nb storage.
r8181
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 checkpoint for a notebook"""
raise NotImplementedError("must be implemented in a subclass")
Brian Granger
Fixing minor things for the Azure backed nb storage.
r8181 def log_info(self):
Paul Ivanov
print info string on interrupt, log it on startup
r10019 self.log.info(self.info_string())
def info_string(self):
return "Serving notebooks"