From 620bf0766658e3914b0d26bb01c0e65211ef3207 Mon Sep 17 00:00:00 2001 From: Tim Paine Date: Tue, 11 Jun 2019 08:54:49 -0400 Subject: [PATCH] adding prelaunch hook --- voila/app.py | 10 ++++++++-- voila/handler.py | 11 +++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/voila/app.py b/voila/app.py index 117b7c15c..3abb0e9eb 100644 --- a/voila/app.py +++ b/voila/app.py @@ -30,7 +30,7 @@ import tornado.web from traitlets.config.application import Application -from traitlets import Unicode, Integer, Bool, Dict, List, default +from traitlets import Unicode, Integer, Bool, Dict, List, Any, default from jupyter_server.services.kernels.kernelmanager import MappingKernelManager from jupyter_server.services.kernels.handlers import KernelHandler, ZMQChannelsHandler @@ -219,6 +219,11 @@ class Voila(Application): cannot be determined reliably by the Jupyter notebook server (proxified or containerized setups for example).""")) + prelaunch_hook = Any(default_value=None, allow_none=True, + help=_("""A function that is called prior to the launch of a new kernel instance + when a user visits the voila webpage. Used for custom user authorization + or any other necessary pre-launch functions.""")) + @property def display_url(self): if self.custom_display_url: @@ -431,7 +436,8 @@ def start(self): 'notebook_path': os.path.relpath(self.notebook_path, self.root_dir), 'nbconvert_template_paths': self.nbconvert_template_paths, 'config': self.config, - 'voila_configuration': self.voila_configuration + 'voila_configuration': self.voila_configuration, + 'prelaunch_hook': self.prelaunch_hook } )) else: diff --git a/voila/handler.py b/voila/handler.py index f230c65a5..a6da19031 100644 --- a/voila/handler.py +++ b/voila/handler.py @@ -24,6 +24,7 @@ def initialize(self, **kwargs): self.nbconvert_template_paths = kwargs.pop('nbconvert_template_paths', []) self.exporter_config = kwargs.pop('config', None) self.voila_configuration = kwargs['voila_configuration'] + self.prelaunch_hook = kwargs.get('prelaunch_hook') @tornado.web.authenticated @tornado.gen.coroutine @@ -54,6 +55,16 @@ def get(self, path=None): # Launch kernel and execute notebook cwd = os.path.dirname(notebook_path) + + if self.prelaunch_hook: + # Allow for preprocessing the notebook. + # Can be used to add auth, do custom formatting/standardization + # of the notebook, raise exceptions, etc + self.prelaunch_hook(self, + notebook=notebook, + kernel_name=kernel_name, + cwd=cwd) + kernel_id = yield tornado.gen.maybe_future(self.kernel_manager.start_kernel(kernel_name=kernel_name, path=cwd)) km = self.kernel_manager.get_kernel(kernel_id) result = executenb(notebook, km=km, cwd=cwd)