handlers.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """Tornado handler for bundling notebooks."""
  2. # Copyright (c) Jupyter Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from . import tools
  5. from notebook.utils import url2path
  6. from notebook.base.handlers import IPythonHandler
  7. from notebook.services.config import ConfigManager
  8. from ipython_genutils.importstring import import_item
  9. from tornado import web, gen
  10. class BundlerHandler(IPythonHandler):
  11. def initialize(self):
  12. """Make tools module available on the handler instance for compatibility
  13. with existing bundler API and ease of reference."""
  14. self.tools = tools
  15. def get_bundler(self, bundler_id):
  16. """
  17. Get bundler metadata from config given a bundler ID.
  18. Parameters
  19. ----------
  20. bundler_id: str
  21. Unique bundler ID within the notebook/bundlerextensions config section
  22. Returns
  23. -------
  24. dict
  25. Bundler metadata with label, group, and module_name attributes
  26. Raises
  27. ------
  28. KeyError
  29. If the bundler ID is unknown
  30. """
  31. cm = ConfigManager()
  32. return cm.get('notebook').get('bundlerextensions', {})[bundler_id]
  33. @web.authenticated
  34. @gen.coroutine
  35. def get(self, path):
  36. """Bundle the given notebook.
  37. Parameters
  38. ----------
  39. path: str
  40. Path to the notebook (path parameter)
  41. bundler: str
  42. Bundler ID to use (query parameter)
  43. """
  44. bundler_id = self.get_query_argument('bundler')
  45. model = self.contents_manager.get(path=url2path(path))
  46. try:
  47. bundler = self.get_bundler(bundler_id)
  48. except KeyError:
  49. raise web.HTTPError(400, 'Bundler %s not enabled' % bundler_id)
  50. module_name = bundler['module_name']
  51. try:
  52. # no-op in python3, decode error in python2
  53. module_name = str(module_name)
  54. except UnicodeEncodeError:
  55. # Encode unicode as utf-8 in python2 else import_item fails
  56. module_name = module_name.encode('utf-8')
  57. try:
  58. bundler_mod = import_item(module_name)
  59. except ImportError:
  60. raise web.HTTPError(500, 'Could not import bundler %s ' % bundler_id)
  61. # Let the bundler respond in any way it sees fit and assume it will
  62. # finish the request
  63. yield gen.maybe_future(bundler_mod.bundle(self, model))
  64. _bundler_id_regex = r'(?P<bundler_id>[A-Za-z0-9_]+)'
  65. default_handlers = [
  66. (r"/bundle/(.*)", BundlerHandler)
  67. ]