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