Django,有关zip文件响应的问题 [英] Django, a problem about zip file response

查看:251
本文介绍了Django,有关zip文件响应的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在django中将请求作为附件发送时遇到问题。我的应用程序将一些数据写入文件并压缩。但是,当我返回附件响应时,浏览器将其下载,但zip文件已损坏。 (原始的zip文件包含我的文件,没有任何错误。)

I have a problem with sending request as attachments in django. My application writes some data to files and zips it. However, when i return an attachment response, the browser downloads it but the zip file is corrupted. (The original zip contains my files and doesn't give any errors.)

我的代码在这里:

        file_path = "/root/Programs/media/statics/schedules/"
        zip_file_name = file_path + "test.zip"
        zip_file = zipfile.ZipFile(zip_file_name, "w")
        for i in range(len(planner_list)):
                file_name = file_path + str(planner_list[i][0].start_date)
                render_to_file('deneme.html',file_name ,{'schedule':schedule})
                zip_file.write(file_name, os.path.basename(file_name),zipfile.ZIP_DEFLATED)
                os.remove(file_name)
        zip_file.close()

        response = HttpResponse(file_path , content_type='application/zip')
        response['Content-Disposition'] = 'attachment; filename=test.zip'
        return response


推荐答案

HttpResponse采用字符串或返回字符串的迭代器(如打开的文件状对象)。您正在向其传递文件路径,因此响应包含一个文件,该文件的内容仅是文件路径,而不是您写入该文件的有效zip内容。您可以只使用 open ,因为 HTTPResponse 对象将为您关闭文件:

HttpResponse takes a string or an iterator returning strings (like an open file-like object). You are passing it the file path, so the response contains a file whose content is just the file path instead of the valid zip content you wrote to the file. You can just use open as the HTTPResponse object will close the file for you:

response = HttpResponse(open(file_path, 'rb'), content_type='application/zip')

引用文档:


最后,您可以通过HttpResponse迭代器而不是字符串。 HttpResponse将立即使用迭代器,将其内容存储为字符串,然后将其丢弃。具有close()方法的对象(例如文件和生成器)将立即关闭。

Finally, you can pass HttpResponse an iterator rather than strings. HttpResponse will consume the iterator immediately, store its content as a string, and discard it. Objects with a close() method such as files and generators are immediately closed.

如果需要将响应从迭代器流式传输到客户端,则必须改用StreamingHttpResponse类。

If you need the response to be streamed from the iterator to the client, you must use the StreamingHttpResponse class instead.

在每个请求上写入磁盘可能会损害服务器的I / O-查看您的代码,所有内容似乎都足够小以容纳内存。您可以使用(C)StringIO(Python3中的BytesIO)代替实际文件:

Writing to disk on every request may hurt your server I/O - looking at your code, everything seems small enough to fit memory. You can use (C)StringIO (BytesIO in Python3) instead of real files:

from io import BytesIO

mem_file = BytesIO()
with zipfile.ZipFile(mem_file, "w") as zip_file:
    for i, planner in enumerate(planner_list):
        file_name = str(planner[0].start_date)
        content = render_to_string('deneme.html', {'schedule':schedule})
    zip_file.writestr(file_name, content)

f.seek(0)  # rewind file pointer just in case
response = HttpResponse(f, content_type='application/zip')

这篇关于Django,有关zip文件响应的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆