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

Python: writing file and using buffer

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

我现在就是这样做的:

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 interface. So, you could try using a BytesIO 的对象来将内容存储在in-memory 缓冲区,而不是写入文件:

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

根据 above-mentioned 函数的确切性质,YMMV。