示例#1
0
    def get_page_config(self):
        config = LabConfig()
        app = self.extensionapp
        base_url = self.settings.get("base_url")

        page_config = {
            "appVersion": version,
            "baseUrl": self.base_url,
            "terminalsAvailable": self.settings.get('terminals_available',
                                                    False),
            "token": self.settings["token"],
            "fullStaticUrl": ujoin(self.base_url, "static", self.name),
            "frontendUrl": ujoin(self.base_url, "classic/"),
        }

        mathjax_config = self.settings.get("mathjax_config",
                                           "TeX-AMS_HTML-full,Safe")
        # TODO Remove CDN usage.
        mathjax_url = self.settings.get(
            "mathjax_url",
            "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js",
        )
        page_config.setdefault("mathjaxConfig", mathjax_config)
        page_config.setdefault("fullMathjaxUrl", mathjax_url)

        # Put all our config in page_config
        for name in config.trait_names():
            page_config[_camelCase(name)] = getattr(app, name)

        # Add full versions of all the urls
        for name in config.trait_names():
            if not name.endswith("_url"):
                continue
            full_name = _camelCase("full_" + name)
            full_url = getattr(app, name)
            if not is_url(full_url):
                # Relative URL will be prefixed with base_url
                full_url = ujoin(base_url, full_url)
            page_config[full_name] = full_url

        labextensions_path = app.extra_labextensions_path + app.labextensions_path
        recursive_update(
            page_config,
            get_page_config(
                labextensions_path,
                logger=self.log,
            ),
        )
        return page_config
示例#2
0
def add_handlers(jupyter_app, config):
    """Add the appropriate handlers to the web app.
    """
    web_app = jupyter_app.web_app
    # Normalize directories.
    for name in config.trait_names():
        if not name.endswith("_dir"):
            continue
        value = getattr(config, name)
        setattr(config, name, value.replace(os.sep, "/"))

    # Normalize urls
    # Local urls should have a leading slash but no trailing slash
    for name in config.trait_names():
        if not name.endswith("_url"):
            continue
        value = getattr(config, name)
        if is_url(value):
            continue
        if not value.startswith("/"):
            value = "/" + value
        if value.endswith("/"):
            value = value[:-1]
        setattr(config, name, value)

    lab_settings = {"lab_config": config}
    if jupyter_app.file_to_run:
        page_config = web_app.settings.setdefault('page_config_data', {})
        page_config.setdefault('notebook_path', jupyter_app.file_to_run)

    handlers = []

    # Set up the main page handler and tree handler.
    base_url = web_app.settings.get("base_url", "/")
    app_path = ujoin(base_url, config.app_url)
    handlers.append((app_path, LabHandler, {
        "lab_config": config
    })
                    #  + notebook_path_regex + '?'
                    )
    if config.app_url != '/':
        # set the URL that will be redirected from `/`
        handlers.append((
            r"/?",
            RedirectWithParams,
            {
                "url": app_path,
                "permanent": False,  # want 302, not 301
            },
        ))

    # Cache all or none of the files depending on the `cache_files` setting.
    no_cache_paths = [] if config.cache_files else ["/"]

    if not jupyter_app.file_to_run:
        # Handle single notebook mode:
        single_mode_path = ujoin(app_path, "single", r".+")
        handlers.append((single_mode_path, LabHandler, {"lab_config": config}))

    # Handle local static assets.
    if config.static_dir:
        static_path = ujoin(base_url, config.static_url, "(.*)")
        handlers.append((
            static_path,
            FileFindHandler,
            {
                "path": config.static_dir,
                "no_cache_paths": no_cache_paths
            },
        ))

    # Handle local settings.
    if config.schemas_dir:
        settings_config = {
            "app_settings_dir": config.app_settings_dir,
            "schemas_dir": config.schemas_dir,
            "settings_dir": config.user_settings_dir,
        }

        # Handle requests for the list of settings. Make slash optional.
        settings_path = ujoin(base_url, config.settings_url, "?")
        handlers.append((settings_path, SettingsHandler, settings_config))

        # Handle requests for an individual set of settings.
        setting_path = ujoin(base_url, config.settings_url,
                             "(?P<schema_name>.+)")
        handlers.append((setting_path, SettingsHandler, settings_config))

    # Handle saved workspaces.
    if config.workspaces_dir:
        # Handle JupyterLab client URLs that include workspaces.
        workspaces_path = ujoin(base_url, config.workspaces_url, r".+")
        if not jupyter_app.file_to_run:
            handlers.append((workspaces_path, LabHandler, {
                "lab_config": config
            }))

        workspaces_config = {
            "workspaces_url": config.workspaces_url,
            "path": config.workspaces_dir,
        }

        # Handle requests for the list of workspaces. Make slash optional.
        workspaces_api_path = ujoin(base_url, config.workspaces_api_url, "?")
        handlers.append(
            (workspaces_api_path, WorkspacesHandler, workspaces_config))

        # Handle requests for an individually named workspace.
        workspace_api_path = ujoin(base_url, config.workspaces_api_url,
                                   "(?P<space_name>.+)")
        handlers.append(
            (workspace_api_path, WorkspacesHandler, workspaces_config))

    # Handle local themes.
    if config.themes_dir:
        themes_url = ujoin(base_url, config.themes_url)
        themes_path = ujoin(themes_url, "(.*)")
        handlers.append((
            themes_path,
            ThemesHandler,
            {
                "themes_url": themes_url,
                "path": config.themes_dir,
                "no_cache_paths": no_cache_paths,
            },
        ))

    web_app.add_handlers(".*$", handlers)
示例#3
0
文件: app.py 项目: jupyter/notebook
    def get_page_config(self):
        config = LabConfig()
        app = self.extensionapp
        base_url = self.settings.get("base_url")
        page_config_data = self.settings.setdefault("page_config_data", {})
        page_config = {
            **page_config_data,
            "appVersion": version,
            "baseUrl": self.base_url,
            "terminalsAvailable": self.settings.get("terminals_available",
                                                    False),
            "token": self.settings["token"],
            "fullStaticUrl": ujoin(self.base_url, "static", self.name),
            "frontendUrl": ujoin(self.base_url, "/"),
            "exposeAppInBrowser": app.expose_app_in_browser,
            "collaborative": app.collaborative,
        }

        if "hub_prefix" in app.serverapp.tornado_settings:
            tornado_settings = app.serverapp.tornado_settings
            hub_prefix = tornado_settings["hub_prefix"]
            page_config["hubPrefix"] = hub_prefix
            page_config["hubHost"] = tornado_settings["hub_host"]
            page_config["hubUser"] = tornado_settings["user"]
            page_config["shareUrl"] = ujoin(hub_prefix, "user-redirect")
            # Assume the server_name property indicates running JupyterHub 1.0.
            if hasattr(app.serverapp, "server_name"):
                page_config["hubServerName"] = app.serverapp.server_name
            api_token = os.getenv("JUPYTERHUB_API_TOKEN", "")
            page_config["token"] = api_token

        server_root = self.settings.get("server_root_dir", "")
        server_root = server_root.replace(os.sep, "/")
        server_root = os.path.normpath(os.path.expanduser(server_root))
        try:
            # Remove the server_root from pref dir
            if self.serverapp.preferred_dir != server_root:
                page_config["preferredPath"] = "/" + os.path.relpath(
                    self.serverapp.preferred_dir, server_root)
            else:
                page_config["preferredPath"] = "/"
        except Exception:
            page_config["preferredPath"] = "/"

        mathjax_config = self.settings.get("mathjax_config",
                                           "TeX-AMS_HTML-full,Safe")
        # TODO Remove CDN usage.
        mathjax_url = self.settings.get(
            "mathjax_url",
            "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js",
        )
        if not url_is_absolute(mathjax_url) and not mathjax_url.startswith(
                self.base_url):
            mathjax_url = ujoin(self.base_url, mathjax_url)

        page_config.setdefault("mathjaxConfig", mathjax_config)
        page_config.setdefault("fullMathjaxUrl", mathjax_url)

        # Put all our config in page_config
        for name in config.trait_names():
            page_config[_camelCase(name)] = getattr(app, name)

        # Add full versions of all the urls
        for name in config.trait_names():
            if not name.endswith("_url"):
                continue
            full_name = _camelCase("full_" + name)
            full_url = getattr(app, name)
            if not is_url(full_url):
                # Relative URL will be prefixed with base_url
                full_url = ujoin(base_url, full_url)
            page_config[full_name] = full_url

        labextensions_path = app.extra_labextensions_path + app.labextensions_path
        recursive_update(
            page_config,
            get_page_config(
                labextensions_path,
                logger=self.log,
            ),
        )
        return page_config
示例#4
0
    def get_page_config(self):
        config = LabConfig()
        app = self.extensionapp
        base_url = self.settings.get("base_url")

        page_config = {
            "appVersion": version,
            "baseUrl": self.base_url,
            "terminalsAvailable": self.settings.get("terminals_available",
                                                    False),
            "token": self.settings["token"],
            "fullStaticUrl": ujoin(self.base_url, "static", self.name),
            "frontendUrl": ujoin(self.base_url, "/"),
            "exposeAppInBrowser": app.expose_app_in_browser,
            "collaborative": app.collaborative,
        }

        if 'hub_prefix' in app.serverapp.tornado_settings:
            tornado_settings = app.serverapp.tornado_settings
            hub_prefix = tornado_settings['hub_prefix']
            page_config['hubPrefix'] = hub_prefix
            page_config['hubHost'] = tornado_settings['hub_host']
            page_config['hubUser'] = tornado_settings['user']
            page_config['shareUrl'] = ujoin(hub_prefix, 'user-redirect')
            # Assume the server_name property indicates running JupyterHub 1.0.
            if hasattr(app.serverapp, 'server_name'):
                page_config['hubServerName'] = app.serverapp.server_name
            api_token = os.getenv('JUPYTERHUB_API_TOKEN', '')
            page_config['token'] = api_token

        mathjax_config = self.settings.get("mathjax_config",
                                           "TeX-AMS_HTML-full,Safe")
        # TODO Remove CDN usage.
        mathjax_url = self.settings.get(
            "mathjax_url",
            "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js",
        )
        if not url_is_absolute(mathjax_url) and not mathjax_url.startswith(
                self.base_url):
            mathjax_url = ujoin(self.base_url, mathjax_url)

        page_config.setdefault("mathjaxConfig", mathjax_config)
        page_config.setdefault("fullMathjaxUrl", mathjax_url)

        # Put all our config in page_config
        for name in config.trait_names():
            page_config[_camelCase(name)] = getattr(app, name)

        # Add full versions of all the urls
        for name in config.trait_names():
            if not name.endswith("_url"):
                continue
            full_name = _camelCase("full_" + name)
            full_url = getattr(app, name)
            if not is_url(full_url):
                # Relative URL will be prefixed with base_url
                full_url = ujoin(base_url, full_url)
            page_config[full_name] = full_url

        labextensions_path = app.extra_labextensions_path + app.labextensions_path
        recursive_update(
            page_config,
            get_page_config(
                labextensions_path,
                logger=self.log,
            ),
        )
        return page_config
示例#5
0
def add_handlers(web_app, config):
    """Add the appropriate handlers to the web app.
    """
    # Normalize directories.
    for name in config.trait_names():
        if not name.endswith('_dir'):
            continue
        value = getattr(config, name)
        setattr(config, name, value.replace(os.sep, '/'))

    # Normalize urls
    # Local urls should have a leading slash but no trailing slash
    for name in config.trait_names():
        if not name.endswith('_url'):
            continue
        value = getattr(config, name)
        if is_url(value):
            continue
        if not value.startswith('/'):
            value = '/' + value
        if value.endswith('/'):
            value = value[:-1]
        setattr(config, name, value)

    # Set up the main page handler and tree handler.
    base_url = web_app.settings.get('base_url', '/')
    app_path = ujoin(base_url, config.app_url)
    handlers = [
        (app_path, LabHandler, {
            'lab_config': config
        }),
        #  + notebook_path_regex + '?'
    ]

    # Cache all or none of the files depending on the `cache_files` setting.
    no_cache_paths = [] if config.cache_files else ['/']

    # Handle local static assets.
    if config.static_dir:
        static_path = ujoin(base_url, config.static_url, '(.*)')
        handlers.append((static_path, FileFindHandler, {
            'path': config.static_dir,
            'no_cache_paths': no_cache_paths
        }))

    # Handle local settings.
    if config.schemas_dir:
        settings_config = {
            'app_settings_dir': config.app_settings_dir,
            'schemas_dir': config.schemas_dir,
            'settings_dir': config.user_settings_dir
        }

        # Handle requests for the list of settings. Make slash optional.
        settings_path = ujoin(base_url, config.settings_url, '?')
        handlers.append((settings_path, SettingsHandler, settings_config))

        # Handle requests for an individual set of settings.
        setting_path = ujoin(base_url, config.settings_url,
                             '(?P<schema_name>.+)')
        handlers.append((setting_path, SettingsHandler, settings_config))

    # Handle saved workspaces.
    if config.workspaces_dir:
        # Handle JupyterLab client URLs that include workspaces.
        workspaces_path = ujoin(base_url, config.workspaces_url, r'.+')
        handlers.append((workspaces_path, LabHandler, {'lab_config': config}))

        workspaces_config = {
            'workspaces_url': config.workspaces_url,
            'path': config.workspaces_dir
        }

        # Handle requests for the list of workspaces. Make slash optional.
        workspaces_api_path = ujoin(base_url, config.workspaces_api_url, '?')
        handlers.append(
            (workspaces_api_path, WorkspacesHandler, workspaces_config))

        # Handle requests for an individually named workspace.
        workspace_api_path = ujoin(base_url, config.workspaces_api_url,
                                   '(?P<space_name>.+)')
        handlers.append(
            (workspace_api_path, WorkspacesHandler, workspaces_config))

    # Handle local themes.
    if config.themes_dir:
        themes_url = ujoin(base_url, config.themes_url)
        themes_path = ujoin(themes_url, '(.*)')
        handlers.append((themes_path, ThemesHandler, {
            'themes_url': themes_url,
            'path': config.themes_dir,
            'no_cache_paths': no_cache_paths
        }))

    web_app.add_handlers('.*$', handlers)