【问题标题】:decompress gzipped data from multipart/form-data with django使用 django 从 multipart/form-data 解压缩 gzipped 数据
【发布时间】:2021-12-28 05:08:30
【问题描述】:

我在尝试在 django 中解压缩 gzip 压缩数据时遇到了很多麻烦。我已经尝试了Download and decompress gzipped file in memory? 中提出的一些解决方案,但我认为我在它如何与 Django 交互方面遇到了困难

我希望能够上传 data.csv.gz,然后如果它是 gzip,将压缩数据提取到 django File 以继续其例程(保存到 FileField

到目前为止,我的序列化程序中有什么

    def create(self, validated_data):
            file: File = validated_data.get("file")
            ext = file.name.split(".")[-1].lower()

            if ext == "gz":
                compressedFile = io.BytesIO()
                compressedFile.write(file.read())

                decompressed_fname = file.name[:-3]
                decompressedFile = gzip.GzipFile(fileobj=compressedFile)
                with open(decompressed_fname, "wb") as outfile:
                    outfile.write(decompressedFile.read())

                with open(decompressed_fname, "rb") as outfile:
                    file = File(outfile)
                    ext = decompressed_fname.split(".")[-1].lower()
...

当我这样做时,当我检查它在磁盘上的内容时,outfile 是空的,并在以后的例程中抛出一个错误

    f.seek(0)
ValueError: seek of closed file

如果我也使用 shutil 也会出现类似的错误

            if ext == "gz":
                compressedFile = io.BytesIO()
                compressedFile.write(file.read())

                decompressed_fname = file.name[:-3]
                import shutil
                shutil.copyfileobj(gzip.GzipFile(fileobj=file), open(decompressed_fname, "wb"))

                with open(decompressed_fname, "rb") as outfile:
                    file = File(outfile)
                    ext = decompressed_fname.split(".")[-1].lower()

我正在使用的 curl 命令:

curl http://0.0.0.0:8000/upload/ -X 'POST' -H "Content-Encoding: gzip" -F "input_type=data" -F "file=@data.csv.gz"

【问题讨论】:

    标签: python django gzip


    【解决方案1】:

    我得到了它的工作:

                if ext == "gz":
                    compressed_file = file.open()
    
                    decompressed_fname = file.name[:-3]
                    decompressedFile = gzip.GzipFile(fileobj=compressed_file)
    
                    f = io.BytesIO()
                    f.write(decompressedFile.read())
    
                    file = File(f, name=decompressed_fname)
                    ext = decompressed_fname.split(".")[-1].lower()
    

    问题是该文件是InMemoryUploadedFile,必须先打开。虽然不太明白

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-20
      • 1970-01-01
      • 2012-08-28
      • 2022-01-22
      • 2011-01-21
      • 2016-04-02
      • 1970-01-01
      相关资源
      最近更新 更多