Python:写入文件并使用缓冲区

发布于 2025-01-11 14:56:59 字数 868 浏览 0 评论 0原文

我正在使用 django 生成个性化文件,但是这样做时会生成一个文件,并且就空间而言,使用它是一件很糟糕的事情。

这就是我现在的做法:

with open(filename, 'wb') as f:
    pdf.write(f) #pdf is an object of pyPDF2 library

with open(filename, 'rb') as f:
    return send_file(data=f, filename=filename) #send_file is a HTTPResponse parametted to download file data

所以在上面的代码中生成了一个文件。

简单的解决方法是下载后删除文件,但我记得在java中使用流对象来处理这种情况。

在 Python 中可以这样做吗?

编辑:

def send_file(data, filename, mimetype=None, force_download=False):
    disposition = 'attachment' if force_download else 'inline'
    filename = os.path.basename(filename)
    response = HttpResponse(data, content_type=mimetype or 'application/octet-stream')
    response['Content-Disposition'] = '%s; filename="%s"' % (disposition, filename)
    return response

I'm using django to generate personalized file, but while doing so a file is generated, and in terms of space using it is quite a poor thing to do.

this is how i do it right now:

with open(filename, 'wb') as f:
    pdf.write(f) #pdf is an object of pyPDF2 library

with open(filename, 'rb') as f:
    return send_file(data=f, filename=filename) #send_file is a HTTPResponse parametted to download file data

So in the code above a file is generated.

The easy fix would be to deleted the file after downloading it, but i remember in java using stream object to handle this case.

Is it possible to do so in Python?

EDIT:

def send_file(data, filename, mimetype=None, force_download=False):
    disposition = 'attachment' if force_download else 'inline'
    filename = os.path.basename(filename)
    response = HttpResponse(data, content_type=mimetype or 'application/octet-stream')
    response['Content-Disposition'] = '%s; filename="%s"' % (disposition, filename)
    return response

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

转身泪倾城 2025-01-18 14:56:59

在不知道 pdf.writesend_file 函数的确切细节的情况下,我希望在这两种情况下它们都会采用符合 BinaryIO 接口。因此,您可以尝试使用 BytesIO 来存储内容在内存缓冲区中,而不是写入文件:

with io.BytesIO() as buf:
    pdf.write(buf)
    buf.seek(0)
    send_file(data=buf, filename=filename)

取决于上述函数的确切性质,YMMV。

Without knowing the exact details of the pdf.write and send_file functions, I expect in both cases they will take an object that conforms to the BinaryIO interface. So, you could try using a BytesIO to store the content in an in-memory buffer, rather than writing out to a file:

with io.BytesIO() as buf:
    pdf.write(buf)
    buf.seek(0)
    send_file(data=buf, filename=filename)

Depending on the exact nature of the above-mentioned functions, YMMV.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文