我正在使用 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
uj5u.com熱心網友回復:
pdf.write在不知道and函式的確切細節的send_file情況下,我希望在這兩種情況下它們都會采用符合BinaryIO介面的物件。因此,您可以嘗試使用BytesIO將內容存盤在記憶體緩沖區中,而不是寫入檔案:
with io.BytesIO() as buf:
pdf.write(buf)
buf.seek(0)
send_file(data=buf, filename=filename)
根據上述功能的確切性質,YMMV.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/437762.html
上一篇:如何使用較新版本的.NET處理Windows服務c#?
下一篇:C函式將檔案內容加載到字串陣列中
