我正在 DRF 代碼中執行以下步驟。
- 捕獲請求中的檔案名
- 在 SFTP 服務器中搜索給定的檔案名。
- 如果檔案在 SFTP 服務器中可用,則將其下載到名為“downloads”的檔案夾中的本地路徑
- 使用 FileResponse 回傳檔案作為回應
我需要洗掉我從 SFTP 下載的檔案或簡單地洗掉下載檔案夾中的所有內容。
實作這一目標的最佳方法是什么?回傳 FileResponse 之前的異步芹菜任務怎么樣?
uj5u.com熱心網友回復:
解決此問題的一種方法是使用 Python 模塊tempfile,它提供臨時檔案,當洗掉 Python 中的所有參考時,這些檔案會自動洗掉。
這是檔案中的一個示例:
>>> import tempfile
# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()
一旦你有了這個檔案物件,你就可以使用FileResponse將它發送回客戶端。
另一種方法是使用cronjob洗掉超過特定天數的檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/395928.html
