Search code examples
jupyter-notebookjupyterjupyter-contrib-nbextensions

How to pass a parameter from the Jupyter backend to a frontend extension


I currently have a value that is stored as an environment variable the environment where a jupyter server is running. I would like to somehow pass that value to a frontend extension. It does not have to read the environment variable in real time, I am fine with just using the value of the variable at startup. Is there a canonical way to pass parameters a frontend extension on startup? Would appreciate an examples of both setting the parameter from the backend and accessing it from the frontend.

[update]

I have posted a solution that works for nbextentions, but I can't seem to find the equivalent pattern for labextensions (typescript), any help there would be much appreciated.


Solution

  • I was able to do this by adding the following code to my jupter_notebook_config.py

    from notebook.services.config import ConfigManager
    
    
    cm = ConfigManager()
    cm.update('notebook', {'variable_being_set': value})
    

    Then I had the parameters defined in my extension in my main.js

        // define default values for config parameters
        var params = {
            variable_being_set : 'default'
        };
    
        // to be called once config is loaded, this updates default config vals
        // with the ones specified by the server's config file
        var update_params = function() {
            var config = Jupyter.notebook.config;
            for (var key in params) {
                if (config.data.hasOwnProperty(key) ){
                    params[key] = config.data[key];
                }
            }
        };
    

    I also have the parameters declared in my main.yaml

    Parameters:
    - name: variable_being_set
      description: ...
      input_type: text
      default: `default_value`
    

    This took some trial and error to find out because there is very little documentation on the ConfigManager class and none of it has an end-to-end example.