我的目标是将一系列字符串解析为一系列文本文件,这些文件压缩为Zip文件,并使用Django的HTTP响应由Web应用程序下载。
在PyCharm本地开发,我的方法输出一个名为" 123.zip"的Zip文件。其中包含6个名为" 123_1"," 123_2等"的单个文件。包含我的短语中的字母没有问题。
问题在于,当我将代码推送到我的网络应用程序并包含Django HTTP响应文件将下载时,但当我去提取它时,它会产生" 123.zip.cpzg"。提取它反过来给了我一个令人沮丧的无限循环中的123.zip(1)。我出错的任何建议?
在本地生产" 123.zip":
的代码def create_text_files1():
JobNumber = "123"
z = zipfile.ZipFile(JobNumber +".zip", mode ="w")
phrase = "A, B, C, D, EF, G"
words = phrase.split(",")
x =0
for word in words:
word.encode(encoding="UTF-8")
x = x + 1
z.writestr(JobNumber +"_" + str(x) + ".txt", word)
z.close()
我的网络应用中该方法的其他部分:
response = HTTPResponse(z, content_type ='application/zip')
response['Content-Disposition'] = "attachment; filename='" + str(jobNumber) + "_AHTextFiles.zip'"
答案 0 :(得分:0)
仔细看看example provided in this answer。
注意打开一个StringIO,使用StringIO作为"File-Like Object"调用zipFile,然后,关键的是,在关闭zipFile之后,在HTTPResponse中返回StringIO。
# Open StringIO to grab in-memory ZIP contents s = StringIO.StringIO() # The zip compressor zf = zipfile.ZipFile(s, "w") # Grab ZIP file from in-memory, make response with correct MIME-type resp = HttpResponse(s.getvalue(), mimetype = "application/x-zip-co mpressed")
我建议你做一些事情。
尝试这样的事情:
def print_nozzle_txt(request):
JobNumber = "123"
phrase = "A, B, C, D, EF, G"
words = phrase.split(",")
x =0
byteStream = io.BytesIO()
with zipfile.ZipFile(byteStream, mode='w', compression=zipfile.ZIP_DEFLATED,) as zf:
for word in words:
word.encode(encoding="UTF-8")
x = x + 1
zf.writestr(JobNumber + "_" + str(x) + ".txt", word)
response = HttpResponse(byteStream.getvalue(), content_type='application/x-zip-compressed')
response['Content-Disposition'] = "attachment; filename='" + str(JobNumber) + "_AHTextFiles.zip'"
return response