zip_bundler.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # Copyright (c) Jupyter Development Team.
  2. # Distributed under the terms of the Modified BSD License.
  3. import os
  4. import io
  5. import zipfile
  6. import notebook.bundler.tools as tools
  7. def _jupyter_bundlerextension_paths():
  8. """Metadata for notebook bundlerextension"""
  9. return [{
  10. 'name': 'notebook_zip_download',
  11. 'label': 'IPython Notebook bundle (.zip)',
  12. 'module_name': 'notebook.bundler.zip_bundler',
  13. 'group': 'download'
  14. }]
  15. def bundle(handler, model):
  16. """Create a zip file containing the original notebook and files referenced
  17. from it. Retain the referenced files in paths relative to the notebook.
  18. Return the zip as a file download.
  19. Assumes the notebook and other files are all on local disk.
  20. Parameters
  21. ----------
  22. handler : tornado.web.RequestHandler
  23. Handler that serviced the bundle request
  24. model : dict
  25. Notebook model from the configured ContentManager
  26. """
  27. abs_nb_path = os.path.join(handler.settings['contents_manager'].root_dir,
  28. model['path'])
  29. notebook_filename = model['name']
  30. notebook_name = os.path.splitext(notebook_filename)[0]
  31. # Headers
  32. zip_filename = os.path.splitext(notebook_name)[0] + '.zip'
  33. handler.set_attachment_header(zip_filename)
  34. handler.set_header('Content-Type', 'application/zip')
  35. # Get associated files
  36. ref_filenames = tools.get_file_references(abs_nb_path, 4)
  37. # Prepare the zip file
  38. zip_buffer = io.BytesIO()
  39. zipf = zipfile.ZipFile(zip_buffer, mode='w', compression=zipfile.ZIP_DEFLATED)
  40. zipf.write(abs_nb_path, notebook_filename)
  41. notebook_dir = os.path.dirname(abs_nb_path)
  42. for nb_relative_filename in ref_filenames:
  43. # Build absolute path to file on disk
  44. abs_fn = os.path.join(notebook_dir, nb_relative_filename)
  45. # Store file under path relative to notebook
  46. zipf.write(abs_fn, nb_relative_filename)
  47. zipf.close()
  48. # Return the buffer value as the response
  49. handler.finish(zip_buffer.getvalue())