Exemple #1
0
    def get(self, path):
        """Bundle the given notebook.

        Parameters
        ----------
        path: str
            Path to the notebook (path parameter)
        bundler: str
            Bundler ID to use (query parameter)
        """
        bundler_id = self.get_query_argument('bundler')
        model = self.contents_manager.get(path=url2path(path))

        try:
            bundler = self.get_bundler(bundler_id)
        except KeyError:
            raise web.HTTPError(400, 'Bundler %s not enabled' % bundler_id)

        module_name = bundler['module_name']
        try:
            # no-op in python3, decode error in python2
            module_name = str(module_name)
        except UnicodeEncodeError:
            # Encode unicode as utf-8 in python2 else import_item fails
            module_name = module_name.encode('utf-8')

        try:
            bundler_mod = import_item(module_name)
        except ImportError:
            raise web.HTTPError(500,
                                'Could not import bundler %s ' % bundler_id)

        # Let the bundler respond in any way it sees fit and assume it will
        # finish the request
        yield gen.maybe_future(bundler_mod.bundle(self, model))
Exemple #2
0
    async def develop_packages(
            self, env: str,
            packages: List[str]) -> Dict[str, List[Dict[str, str]]]:
        """Install packages in pip editable mode in an environment.

        Args:
            env (str): Environment name
            packages (List[str]): List of packages to install

        Returns:
            Dict[str, str]: Install command output.
        """
        envs = await self.list_envs()
        if "error" in envs:
            return envs

        env_rootpath = None
        for e in envs["environments"]:
            if e["name"] == env:
                env_rootpath = e
                break

        result = []
        if env_rootpath:
            if sys.platform == "win32":
                python_cmd = os.path.join(env_rootpath["dir"], "python")
            else:
                python_cmd = os.path.join(env_rootpath["dir"], "bin", "python")

            for path in packages:
                realpath = os.path.realpath(os.path.expanduser(path))
                if not os.path.exists(realpath):
                    # Convert jupyterlab path to local path if the path does not exists
                    realpath = os.path.realpath(
                        os.path.join(self._root_dir, url2path(path)))
                    if not os.path.exists(realpath):
                        return {
                            "error": "Unable to find path {}.".format(path)
                        }

                ans = await self._execute(
                    python_cmd,
                    "-m",
                    "pip",
                    "install",
                    "--progress-bar",
                    "off",
                    "-e",
                    realpath,
                )
                rcode, output = ans
                if rcode > 0:
                    return {"error": output}
                feedback = {"path": path, "output": output}
                result.append(feedback)
        return {"packages": result}
Exemple #3
0
 async def post(self):
     cm = self.contents_manager
     data = self.get_json_body()
     filename = data["filename"]
     reference = data["reference"]
     top_repo_path = os.path.join(cm.root_dir,
                                  url2path(data["top_repo_path"]))
     response = await self.git.get_content_at_reference(
         filename, reference, top_repo_path)
     self.finish(json.dumps(response))
Exemple #4
0
 async def post(self):
     cm = self.contents_manager
     data = self.get_json_body()
     filename = data["filename"]
     prev_ref = data["prev_ref"]
     curr_ref = data["curr_ref"]
     top_repo_path = os.path.join(cm.root_dir,
                                  url2path(data["top_repo_path"]))
     response = await self.git.diff_content(filename, prev_ref, curr_ref,
                                            top_repo_path)
     self.finish(json.dumps(response))
    async def get(self, archive_path, include_body=False):

        # /extract-archive/ requests must originate from the same site
        self.check_xsrf_cookie()
        cm = self.contents_manager

        if cm.is_hidden(archive_path) and not cm.allow_hidden:
            self.log.info("Refusing to serve hidden file, via 404 Error")
            raise web.HTTPError(404)

        archive_path = pathlib.Path(cm.root_dir) / url2path(archive_path)

        await ioloop.IOLoop.current().run_in_executor(None,
                                                      self.extract_archive,
                                                      archive_path)

        self.finish()
Exemple #6
0
    def url2localpath(
        self,
        path: str,
        with_contents_manager: bool = False
    ) -> Union[str, Tuple[str, ContentsManager]]:
        """Get the local path from a JupyterLab server path.

        Optionally it can also return the contents manager for that path.
        """
        cm = self.contents_manager

        # Handle local manager of hybridcontents.HybridContentsManager
        if hybridcontents is not None and isinstance(
                cm, hybridcontents.HybridContentsManager):
            _, cm, path = hybridcontents.hybridmanager._resolve_path(
                path, cm.managers)

        local_path = os.path.join(os.path.expanduser(cm.root_dir),
                                  url2path(path))
        return (local_path, cm) if with_contents_manager else local_path
    async def get(self, archive_path, include_body=False):

        # /directories/ requests must originate from the same site
        self.check_xsrf_cookie()
        cm = self.contents_manager

        if cm.is_hidden(archive_path) and not cm.allow_hidden:
            self.log.info("Refusing to serve hidden file, via 404 Error")
            raise web.HTTPError(404)

        archive_token = self.get_argument("archiveToken")
        archive_format = self.get_argument("archiveFormat", "zip")
        if archive_format not in SUPPORTED_FORMAT:
            self.log.error("Unsupported format {}.".format(archive_format))
            raise web.HTTPError(404)
        # Because urls can only pass strings, must check if string value is true
        # or false. If it is not either value, then it is an invalid argument
        # and raise http error 400.
        if self.get_argument("followSymlinks", "true") == "true":
            follow_symlinks = True
        elif self.get_argument("followSymlinks", "true") == "false":
            follow_symlinks = False
        else:
            raise web.HTTPError(400)
        if self.get_argument("downloadHidden", "false") == "true":
            download_hidden = True
        elif self.get_argument("downloadHidden", "false") == "false":
            download_hidden = False
        else:
            raise web.HTTPError(400)

        archive_path = pathlib.Path(cm.root_dir) / url2path(archive_path)
        archive_name = archive_path.name
        archive_filename = archive_path.with_suffix(
            ".{}".format(archive_format)).name

        self.log.info("Prepare {} for archiving and downloading.".format(
            archive_filename))
        self.set_header("content-type", "application/octet-stream")
        self.set_header("cache-control", "no-cache")
        self.set_header("content-disposition",
                        "attachment; filename={}".format(archive_filename))

        self.canceled = False
        self.flush_cb = ioloop.PeriodicCallback(self.flush,
                                                ARCHIVE_DOWNLOAD_FLUSH_DELAY)
        self.flush_cb.start()

        args = (
            archive_path,
            archive_format,
            archive_token,
            follow_symlinks,
            download_hidden,
        )
        await ioloop.IOLoop.current().run_in_executor(
            None, self.archive_and_download, *args)

        if self.canceled:
            self.log.info("Download canceled.")
        else:
            self.flush()
            self.log.info("Finished downloading {}.".format(archive_filename))

        self.set_cookie("archiveToken", archive_token)
        self.flush_cb.stop()
        self.finish()