tarball_bundler.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # Copyright (c) Jupyter Development Team.
  2. # Distributed under the terms of the Modified BSD License.
  3. import os
  4. import io
  5. import tarfile
  6. import nbformat
  7. def _jupyter_bundlerextension_paths():
  8. """Metadata for notebook bundlerextension"""
  9. return [{
  10. # unique bundler name
  11. "name": "tarball_bundler",
  12. # module containing bundle function
  13. "module_name": "notebook.bundler.tarball_bundler",
  14. # human-redable menu item label
  15. "label" : "Notebook Tarball (tar.gz)",
  16. # group under 'deploy' or 'download' menu
  17. "group" : "download",
  18. }]
  19. def bundle(handler, model):
  20. """Create a compressed tarball containing the notebook document.
  21. Parameters
  22. ----------
  23. handler : tornado.web.RequestHandler
  24. Handler that serviced the bundle request
  25. model : dict
  26. Notebook model from the configured ContentManager
  27. """
  28. notebook_filename = model['name']
  29. notebook_content = nbformat.writes(model['content']).encode('utf-8')
  30. notebook_name = os.path.splitext(notebook_filename)[0]
  31. tar_filename = '{}.tar.gz'.format(notebook_name)
  32. info = tarfile.TarInfo(notebook_filename)
  33. info.size = len(notebook_content)
  34. with io.BytesIO() as tar_buffer:
  35. with tarfile.open(tar_filename, "w:gz", fileobj=tar_buffer) as tar:
  36. tar.addfile(info, io.BytesIO(notebook_content))
  37. handler.set_attachment_header(tar_filename)
  38. handler.set_header('Content-Type', 'application/gzip')
  39. # Return the buffer value as the response
  40. handler.finish(tar_buffer.getvalue())