如果我從臨時檔案包裝器中洗掉 pdf 檔案創建,我可以發送一個正確的檔案,但是當我用臨時檔案包裝時,我收到此錯誤:
AttributeError: 'bytes' 物件沒有屬性 'read'
我試圖從我的檔案路徑中洗掉 .read() 但后來我收到另一個關于嘗試讀取關閉檔案的錯誤。我在網上查看了燒瓶 send_file ,似乎在 tmp 檔案上使用 send_file 存在問題。有沒有人有解決辦法?我不想創建一個檔案,然后在發送后手動將其洗掉,我想將其保留為臨時檔案
with tempfile.TemporaryFile() as fp:
PDF.dumps(fp, pdf)
return send_file(fp.read(), attachment_filename="invoice" str(invoice["id"]) ".pdf", as_attachment=True)
uj5u.com熱心網友回復:
使用 aTemporaryFile作為背景關系管理器,一旦塊結束,檔案就會關閉。該send_file呼叫不會立即讀取檔案 - 它只是回傳一個物件,該物件使您的檔案在背景關系管理器關閉后稍后被讀取。
根據tempfile檔案,當檔案句柄關閉時檔案被清理,并且 PEP 333,WSGI 規范,指定兼容的實作必須close(),所以我們可以在沒有背景關系管理器的情況下做到這一點:
tmp = tempfile.TemporaryFile()
tmp.write(b'some content')
tmp.seek(0)
return send_file(tmp, attachment_filename='example.txt')
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/352720.html
