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



我正在使用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

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

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

根据上述功能的确切性质,YMMV。

最新更新