Search code examples
jupyter-lab

Access kernel environment variables from a JupyterLab extension


I have a button extension for JupyterLab.
This extension gives the option to run tools with one click.

I want to show a value from the kernel ENV, let's say 'JOB_NAME' for the opened notebook.

How can I access this ENV variable from the extension TypeScript Code?


Solution

  • Your frontend extension will require a server extension to grab the environment variable Here's a quick example for the handlers.py file:

    import json
    import os
    
    from jupyter_server.base.handlers import APIHandler
    from jupyter_server.utils import url_path_join
    import tornado
    
    class RouteHandler(APIHandler):
        # The following decorator should be present on all verb methods (head, get, post,
        # patch, put, delete, options) to ensure only authorized user can request the
        # Jupyter server
        @tornado.web.authenticated
        def get(self):
            actual_key = os.getenv('ENV_VARIABLE')
            self.finish(json.dumps({
                "data": actual_key
            }))
    
    
    def setup_handlers(web_app):
        host_pattern = ".*$"
    
        base_url = web_app.settings["base_url"]
        route_pattern = url_path_join(base_url, "serverextension", "get_example")
        handlers = [(route_pattern, RouteHandler)]
        web_app.add_handlers(host_pattern, handlers)
    
    

    Credit: https://discourse.jupyter.org/t/read-environment-variables-from-jupyter/8878/7