Ejemplo n.º 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 maybe_future(bundler_mod.bundle(self, model))
Ejemplo n.º 2
0
    def get(self):
        '''
        Converts a notebook into an application bundle. Respects the `type`
        query  argument as the type of bundle to produce. Responds with the
        bundle or a pointer to it depending on the type.

        :arg notebook: path to the notebook relative to the notebook directory
            root
        :arg type: `bluemix` generates a Bluemix application
        '''
        notebook = self.get_query_argument('notebook')
        bundle_type = self.get_query_argument('type')
        abs_nb_path = os.path.join(self.nb_dir, url2path(notebook))

        if not os.path.isfile(abs_nb_path):
            raise web.HTTPError(400, 'notebook not found')

        if bundle_type == 'bluemix':
            self._get_bluemix_app(abs_nb_path)
        elif bundle_type == 'zip':
            self._get_app_zip(abs_nb_path)
        elif bundle_type == 'dashboard':
            self._get_local_app(abs_nb_path)
        elif bundle_type == 'ipynb':
            self._get_ipynb_with_files(abs_nb_path)
        else:
            raise web.HTTPError(400, 'unknown bundle type')
Ejemplo n.º 3
0
    def get(self, bundler_id):
        '''
        Executes the requested bundler on the given notebook.

        :param bundler_id: Unique ID of an installed bundler
        :arg notebook: Path to the notebook relative to the notebook directory
            root
        '''
        notebook = self.get_query_argument('notebook')
        abs_nb_path = os.path.join(self.notebook_dir, url2path(notebook))
        try:
            bundler = self.get_bundler(bundler_id)
        except KeyError:
            raise web.HTTPError(404, 'Bundler %s not found' % 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, abs_nb_path))
    def get(self, path):
        cm = self.contents_manager
        fullpath = os.path.join(cm.root_dir, url2path(path))

        # Headers
        paths = os.path.split(fullpath)
        name = paths[-1]
        zip_filename = name + '.zip'
        self.set_attachment_header(zip_filename)
        self.set_header('Content-Type', 'application/zip')

        # Prepare the zip file
        zip_buffer = io.BytesIO()
        zipf = zipfile.ZipFile(zip_buffer,
                               mode='w',
                               compression=zipfile.ZIP_DEFLATED)

        prefix = os.path.join(*paths[:-1])
        for root, dirs, files in os.walk(fullpath):
            relative = os.path.relpath(root, prefix)
            for file in files:
                zipf.write(os.path.join(root, file),
                           os.path.join(relative, file))

        zipf.close()

        # Return the buffer value as the response
        self.finish(zip_buffer.getvalue())
Ejemplo n.º 5
0
    def get(self, bundler_id):
        """
        Executes the requested bundler on the given notebook.

        :param bundler_id: Unique ID of an installed bundler
        :arg notebook: Path to the notebook relative to the notebook directory
            root
        """
        notebook = self.get_query_argument("notebook")
        abs_nb_path = os.path.join(self.notebook_dir, url2path(notebook))
        try:
            bundler = self.get_bundler(bundler_id)
        except KeyError:
            raise web.HTTPError(404, "Bundler %s not found" % 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, abs_nb_path))
Ejemplo n.º 6
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))
Ejemplo n.º 7
0
    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 = os.path.join(cm.root_dir, url2path(archive_path))

        archive_path = pathlib.Path(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)
        yield 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()
Ejemplo n.º 8
0
    def _get_realpath(self, path: str) -> Path:
        """Tranform notebook path to absolute path.

        Args:
            path (str): Path to be transformed

        Returns:
            Path: Absolute path
        """
        return Path(self.contents_manager.root_dir).absolute() / url2path(path)
Ejemplo n.º 9
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))
Ejemplo n.º 10
0
    async def post(self, path: str = ""):
        """Create a new file in the specified path.

        POST /jupyter-project/files/<parent-file-path>
            Creates a new file applying the parameters to the Jinja template.

        Request json body:
            Dictionary of parameters for the Jinja template.
        """
        if self.template is None:
            raise tornado.web.HTTPError(
                404, reason="File Jinja template not found.")

        cm = self.contents_manager
        params = self.get_json_body()

        try:
            default_name = self.default_name.render(**params)
        except TemplateError as error:
            self.log.warning(
                f"Fail to render the default name for template '{self.template.name}'"
            )
            default_name = cm.untitled_file

        ext = "".join(Path(self.template.name).suffixes)
        filename = default_name + ext
        filename = cm.increment_filename(filename, path)
        fullpath = url_path_join(path, filename)

        realpath = Path(cm.root_dir).absolute() / url2path(fullpath)
        if not realpath.parent.exists():
            realpath.parent.mkdir(parents=True)

        current_loop = tornado.ioloop.IOLoop.current()
        try:
            content = await current_loop.run_in_executor(
                None, functools.partial(self.template.render, **params))
            realpath.write_text(content)
        except (OSError, TemplateError) as error:
            raise tornado.web.HTTPError(
                500,
                log_message=
                f"Fail to generate the file from template {self.template.name}.",
                reason=repr(error),
            )

        model = cm.get(fullpath, content=False, type="file", format="text")
        self.set_status(201)
        self.finish(json.dumps(model, default=date_default))
Ejemplo n.º 11
0
    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 = os.path.join(cm.root_dir, url2path(archive_path))
        archive_path = pathlib.Path(archive_path)

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

        self.finish()
Ejemplo n.º 12
0
    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)

        archive_path = os.path.join(cm.root_dir, url2path(archive_path))

        archive_path = pathlib.Path(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)
        yield 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()
Ejemplo n.º 13
0
    def get(self, bundler_id):
        '''
        Executes the requested bundler on the given notebook.

        :param bundler_id: Unique ID of an installed bundler
        :arg notebook: Path to the notebook relative to the notebook directory
            root
        '''
        notebook = self.get_query_argument('notebook')
        abs_nb_path = os.path.join(self.notebook_dir, url2path(notebook))
        try:
            bundler = self.get_bundler(bundler_id)
        except KeyError:
            raise web.HTTPError(404, 'Bundler %s not found' % bundler_id)
        try:
            bundler_mod = import_item(bundler['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, abs_nb_path))