##// END OF EJS Templates
MAINT: Return dicts from CheckpointManager.get_checkpoint....
MAINT: Return dicts from CheckpointManager.get_checkpoint. The output is going to get converted to a dict anyway, and this makes it easier to pipe output from a CheckpointManager directly to a ContentsManager.

File last commit:

r19027:034353ef
r19825:f587966f
Show More
handlers.py
149 lines | 4.7 KiB | text/x-python | PythonLexer
MinRK
teach contents service about non-notebook files
r17525 """Tornado handlers for nbconvert."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
Thomas Kluyver
Serve nbconvert output as zip when it has multiple files
r13919 import io
Thomas Kluyver
Add HTTP handlers for nbconvert
r13827 import os
Thomas Kluyver
Serve nbconvert output as zip when it has multiple files
r13919 import zipfile
Thomas Kluyver
Add HTTP handlers for nbconvert
r13827
from tornado import web
MinRK
move `/files/` redirect to base handlers...
r17533 from ..base.handlers import (
IPythonHandler, FilesRedirectHandler,
notebook_path_regex, path_regex,
)
MinRK
don't use nbformat.current in IPython.html...
r18607 from IPython.nbformat import from_dict
MinRK
allow notebook to start without nbconvert...
r13946
Thomas Kluyver
Serve nbconvert output as zip when it has multiple files
r13919 from IPython.utils.py3compat import cast_bytes
def find_resource_files(output_files_dir):
files = []
for dirpath, dirnames, filenames in os.walk(output_files_dir):
files.extend([os.path.join(dirpath, f) for f in filenames])
return files
def respond_zip(handler, name, output, resources):
"""Zip up the output and resource files and respond with the zip file.
Returns True if it has served a zip file, False if there are no resource
files, in which case we serve the plain output file.
"""
# Check if we have resource files we need to zip
output_files = resources.get('outputs', None)
if not output_files:
return False
# Headers
zip_filename = os.path.splitext(name)[0] + '.zip'
handler.set_header('Content-Disposition',
'attachment; filename="%s"' % zip_filename)
handler.set_header('Content-Type', 'application/zip')
# Prepare the zip file
buffer = io.BytesIO()
zipf = zipfile.ZipFile(buffer, mode='w', compression=zipfile.ZIP_DEFLATED)
Thomas Kluyver
Add the . into file_extension
r19027 output_filename = os.path.splitext(name)[0] + resources['output_extension']
Thomas Kluyver
Serve nbconvert output as zip when it has multiple files
r13919 zipf.writestr(output_filename, cast_bytes(output, 'utf-8'))
for filename, data in output_files.items():
zipf.writestr(os.path.basename(filename), data)
zipf.close()
handler.finish(buffer.getvalue())
return True
Thomas Kluyver
Add HTTP handlers for nbconvert
r13827
MinRK
allow notebook to start without nbconvert...
r13946 def get_exporter(format, **kwargs):
"""get an exporter, raising appropriate errors"""
# if this fails, will raise 500
try:
from IPython.nbconvert.exporters.export import exporter_map
except ImportError as e:
raise web.HTTPError(500, "Could not import nbconvert: %s" % e)
try:
Exporter = exporter_map[format]
except KeyError:
# should this be 400?
raise web.HTTPError(404, u"No exporter for format: %s" % format)
MinRK
turn missing dependencies in nbconvert to 500 errors...
r14044 try:
return Exporter(**kwargs)
except Exception as e:
raise web.HTTPError(500, "Could not construct Exporter: %s" % e)
MinRK
allow notebook to start without nbconvert...
r13946
Thomas Kluyver
Add HTTP handlers for nbconvert
r13827 class NbconvertFileHandler(IPythonHandler):
SUPPORTED_METHODS = ('GET',)
@web.authenticated
MinRK
Remove separate 'path', 'name' in Contents API...
r18749 def get(self, format, path):
MinRK
allow notebook to start without nbconvert...
r13946
MinRK
support pdf export in the notebook UI
r16266 exporter = get_exporter(format, config=self.config, log=self.log)
Thomas Kluyver
Add HTTP handlers for nbconvert
r13827
path = path.strip('/')
Thomas Kluyver
Rename get_model() to get()
r18791 model = self.contents_manager.get(path=path)
MinRK
Remove separate 'path', 'name' in Contents API...
r18749 name = model['name']
Thomas Kluyver
Add HTTP handlers for nbconvert
r13827
MinRK
use NotebookManager APIs in nbconvert handler
r15421 self.set_header('Last-Modified', model['last_modified'])
MinRK
catch pandoc failures in nbconvert handlers
r13940
try:
MinRK
use NotebookManager APIs in nbconvert handler
r15421 output, resources = exporter.from_notebook_node(model['content'])
MinRK
catch pandoc failures in nbconvert handlers
r13940 except Exception as e:
raise web.HTTPError(500, "nbconvert failed: %s" % e)
Thomas Kluyver
Serve nbconvert output as zip when it has multiple files
r13919
if respond_zip(self, name, output, resources):
return
Thomas Kluyver
Add MIME types to nbconvert exporters
r13830 # Force download if requested
Thomas Kluyver
Add menu entries for getting converted views of a notebook
r13829 if self.get_argument('download', 'false').lower() == 'true':
Thomas Kluyver
Add the . into file_extension
r19027 filename = os.path.splitext(name)[0] + resources['output_extension']
Thomas Kluyver
Add menu entries for getting converted views of a notebook
r13829 self.set_header('Content-Disposition',
Thomas Kluyver
Serve nbconvert output as zip when it has multiple files
r13919 'attachment; filename="%s"' % filename)
Thomas Kluyver
Add MIME types to nbconvert exporters
r13830 # MIME type
Thomas Kluyver
Condense raw_mimetype and mime_type traitlets into output_mimetype
r13832 if exporter.output_mimetype:
self.set_header('Content-Type',
'%s; charset=utf-8' % exporter.output_mimetype)
Thomas Kluyver
Add MIME types to nbconvert exporters
r13830
Thomas Kluyver
Add HTTP handlers for nbconvert
r13827 self.finish(output)
class NbconvertPostHandler(IPythonHandler):
SUPPORTED_METHODS = ('POST',)
MinRK
Remove separate 'path', 'name' in Contents API...
r18749 @web.authenticated
Thomas Kluyver
Add HTTP handlers for nbconvert
r13827 def post(self, format):
MinRK
allow notebook to start without nbconvert...
r13946 exporter = get_exporter(format, config=self.config)
Thomas Kluyver
Add HTTP handlers for nbconvert
r13827
model = self.get_json_body()
MinRK
update html/js to nbformat 4
r18584 name = model.get('name', 'notebook.ipynb')
MinRK
use from_dict for dict->notebook...
r18601 nbnode = from_dict(model['content'])
MinRK
catch pandoc failures in nbconvert handlers
r13940
try:
output, resources = exporter.from_notebook_node(nbnode)
except Exception as e:
raise web.HTTPError(500, "nbconvert failed: %s" % e)
Thomas Kluyver
Serve nbconvert output as zip when it has multiple files
r13919
MinRK
update html/js to nbformat 4
r18584 if respond_zip(self, name, output, resources):
Thomas Kluyver
Serve nbconvert output as zip when it has multiple files
r13919 return
Thomas Kluyver
Add MIME types to nbconvert exporters
r13830 # MIME type
Thomas Kluyver
Condense raw_mimetype and mime_type traitlets into output_mimetype
r13832 if exporter.output_mimetype:
self.set_header('Content-Type',
Thomas Kluyver
Serve nbconvert output as zip when it has multiple files
r13919 '%s; charset=utf-8' % exporter.output_mimetype)
Thomas Kluyver
Add MIME types to nbconvert exporters
r13830
Thomas Kluyver
Add HTTP handlers for nbconvert
r13827 self.finish(output)
MinRK
move `/files/` redirect to base handlers...
r17533
Thomas Kluyver
Add HTTP handlers for nbconvert
r13827 #-----------------------------------------------------------------------------
# URL to handler mappings
#-----------------------------------------------------------------------------
_format_regex = r"(?P<format>\w+)"
Thomas Kluyver
Move notebook URL fragment regexen into IPython.html.base.handlers
r13916
Thomas Kluyver
Add HTTP handlers for nbconvert
r13827
default_handlers = [
Thomas Kluyver
Move notebook URL fragment regexen into IPython.html.base.handlers
r13916 (r"/nbconvert/%s%s" % (_format_regex, notebook_path_regex),
Thomas Kluyver
Add HTTP handlers for nbconvert
r13827 NbconvertFileHandler),
(r"/nbconvert/%s" % _format_regex, NbconvertPostHandler),
MinRK
move `/files/` redirect to base handlers...
r17533 (r"/nbconvert/html%s" % path_regex, FilesRedirectHandler),
Spencer Nelson
Remove unused imports
r16525 ]