From d5f47d2d5384cfbf3d336a2e01419bda8fbe7739 Mon Sep 17 00:00:00 2001 From: Peter Parente Date: Sat, 2 Jul 2016 23:16:06 -0400 Subject: [PATCH] Add zip bundler as an example (c) Copyright IBM Corp. 2016 --- notebook/bundler/zip_bundler.py | 59 +++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 notebook/bundler/zip_bundler.py diff --git a/notebook/bundler/zip_bundler.py b/notebook/bundler/zip_bundler.py new file mode 100644 index 000000000..8885728f2 --- /dev/null +++ b/notebook/bundler/zip_bundler.py @@ -0,0 +1,59 @@ +# Copyright (c) Jupyter Development Team. +# Distributed under the terms of the Modified BSD License. +import os +import io +import zipfile + +def _jupyter_bundlerextension_paths(): + """Metadata for notebook bundlerextension""" + return [{ + 'name': 'notebook_zip_download', + 'label': 'IPython Notebook bundle (.zip)', + 'module_name': 'notebook.bundler.zip_bundler', + 'group': 'download' + }] + +def bundle(handler, model): + """Create a zip file containing the original notebook and files referenced + from it. Retain the referenced files in paths relative to the notebook. + Return the zip as a file download. + + Assumes the notebook and other files are all on local disk. + + Parameters + ---------- + handler : tornado.web.Handler + Handler that serviced the bundle request + model : dict + Notebook model from a ContentManager + """ + abs_nb_path = os.path.join(handler.settings['contents_manager'].root_dir, + model['path']) + notebook_filename = model['name'] + notebook_name = os.path.splitext(notebook_filename)[0] + + # Headers + zip_filename = os.path.splitext(notebook_name)[0] + '.zip' + handler.set_header('Content-Disposition', + 'attachment; filename="%s"' % zip_filename) + handler.set_header('Content-Type', 'application/zip') + + # Get associated files + ref_filenames = handler.tools.get_file_references(abs_nb_path, 4) + + # Prepare the zip file + zip_buffer = io.BytesIO() + zipf = zipfile.ZipFile(zip_buffer, mode='w', compression=zipfile.ZIP_DEFLATED) + zipf.write(abs_nb_path, notebook_filename) + + notebook_dir = os.path.dirname(abs_nb_path) + for nb_relative_filename in ref_filenames: + # Build absolute path to file on disk + abs_fn = os.path.join(notebook_dir, nb_relative_filename) + # Store file under path relative to notebook + zipf.write(abs_fn, nb_relative_filename) + + zipf.close() + + # Return the buffer value as the response + handler.finish(zip_buffer.getvalue()) \ No newline at end of file