Trying to pack list UploadFile into zip resulting in empty files with 0 bytes length

29 views Asked by At

I have a HTTP server written in FASTAPI and I'm trying to implement the following functionality:

  1. User can upload description file (format json) and list of files with any extension.
  2. Description file is checked
  3. All files (including description file) are packed into zip archive. So far everything works somehow with one problem - after packing into .zip all files have a length of 0 bytes, but the filenames are correct. What can be a reason for that? Here are my functions that cover this functionality:
@router.post("/manual_upload", status_code=status.HTTP_201_CREATED)
def add_package_manual(
    description_file: UploadFile,
    files: list[UploadFile] = File(...),
) -> Package:
    return PackageManager.create_package_from_files(
        filename=filename,
        description_file=description_file,
        files=files,
    )
    def create_package_from_files(
        description_file: UploadFile,
        files: list[UploadFile] = File(...),
    ) -> Package:
        print("Creating package from files...")

        file_names: list[str] = []

        # create temporary folder to store data
        try:
            with tempfile.TemporaryDirectory() as temp_dir:
                try:
                    if description_file.content_type != "application/json":
                        raise HTTPException(
                            422,
                            detail="Invalid description file extension. Expecting json.",
                        )
                    contents = json.loads(description_file.file.read())
                    try:
                        description = PackageManager.description_json_to_model(contents)
                    except ValidationError as e:
                        HTTPException(422, detail="Invalid description file")
                except Exception as e:
                    raise e
                finally:
                    description_file.file.close()

                with open(f := f"{temp_dir}/{description_file.filename}", "wb+"):
                    assert isinstance(description_file.filename, str)
                    file_names.append(description_file.filename)

                for file in files:
                    try:
                        with open(
                            f := f"{temp_dir}/{file.filename}", "wb+"
                        ) as file_object:
                            assert isinstance(file.filename, str)
                            file_names.append(file.filename)
                    except HTTPException as e:
                        raise HTTPException(
                            415, detail="There was an error uploading the file(s)"
                        )
                    finally:
                        file.file.close()

                lst = os.listdir(temp_dir)
                print("files in temp dir:", lst)
                shutil.make_archive("data/packages/kurwa", "zip", temp_dir)
        except FileNotFoundError as file_not_found_error:
            raise HTTPException(
                status_code=404,
                detail="Couldn't find a file: " + str(file_not_found_error),
            )
        except IsADirectoryError as is_a_directory_error:
            raise HTTPException(
                status_code=400,
                detail="Given path is a directory, expecting file: "
                + str(is_a_directory_error),
            )

What's weird, print("files in temp dir:", lst) lists all the files correctly, but after packing it into kurwa.zip it looks like this:

enter image description here

0

There are 0 answers