【发布时间】: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"
【问题讨论】: