예제 #1
0
    def downloads(handler: IPythonHandler):
        file_paths = get_file_paths(handler)
        if file_paths:
            if len(file_paths) == 0:
                handler.set_status(400, f"Files not found.")
                handler.finish()
                return

            if len(file_paths) == 1:
                send_files(handler, file_paths[0],
                           file_paths[0].split('/')[-1])

            else:
                with TemporaryDirectory() as dir_path:
                    tar_gz_file_name = f'{str(uuid.uuid4())}.tar.gz'
                    tar_gz_file_path = os.path.join(dir_path, tar_gz_file_name)
                    with tarfile.open(tar_gz_file_path, mode='w:gz') as tar:
                        for file_path in file_paths:
                            tar.add(
                                file_path,
                                os.path.join('download',
                                             file_path.split('/')[-1]))

                    send_files(handler, tar_gz_file_path, tar_gz_file_name)

        handler.finish()
예제 #2
0
    def uploads(handler: IPythonHandler):
        files = handler.request.files
        files_saved = 0

        if len(files) == 0 or 'file' not in files:
            handler.set_status(
                400,
                f"Can't find 'file' or filename is empty. Files received {len(files)}"
            )
        else:

            for f in files['file']:
                if not allowed_file(f.filename):
                    logging.warn(
                        f"Can't store file {f.filename}. Extension not allowed"
                    )
                    continue

                # Save to file
                filename = f.filename
                file_path = os.path.join(UPLOAD_FOLDER_PATH, filename)

                with open(file_path, 'wb') as zf:
                    zf.write(f['body'])

                files_saved += 1

                if filename.endswith('.zip'):
                    with ZipFile(file_path) as zipObj:
                        zipObj.extractall(UPLOAD_FOLDER_PATH)

                elif filename.endswith('.tar.gz'):
                    with tarfile.open(file_path, mode='r:gz') as tar:
                        tar.extractall(UPLOAD_FOLDER_PATH)

                elif filename.endswith('.gz'):
                    with gzip.open(file_path, "rb") as gz, open(
                            file_path.replace('.gz', ''), 'wb') as ff:
                        shutil.copyfileobj(gz, ff)

            handler.set_status(
                200,
                f"Number of files saved: {files_saved}. Number of files sent: {len(files['file'])}"
            )

        handler.finish()