[英]Sanic Python: Delete File after sending it to a client
我正在使用 Sanic 運行 Python 服務器,當客戶端請求文件時,服務器會創建此文件並將其發送給客戶端。 目前,我一直在使用中間件: @app.listener('before_server_stop')
在服務器停止時清理這些文件。
顯然,這個解決方案並不好,我寧願在將響應與文件一起發送給客戶端后立即清理它們。 有沒有辦法做到這一點?
有問題的代碼:
@app.route('/getFiles', methods=['GET'])
async def getFiles(request):
//create file
if os.path.isfile(id+'.txt'):
return await response.file(id+'.txt')
// -> best would be to delete file here
@app.listener('before_server_stop')
//delete all files
謝謝。
您可以使用os.remove()刪除文件
if os.path.exists(id+'.txt'):
os.remove(id+'.txt')
您的案例中的步驟:
1-將數據文件加載/讀取到變量中
2 - 刪除文件
3 -將變量內容作為 HTTP 文件響應返回,檢查 Sanic 中的 Django 中是否是這樣的:
response = HttpResponse(data, [content_type]='text/plain')
response['Content-Disposition'] = 'attachment; filename="myfile.txt"'
return response
檢查內容類型/MIME 類型的文件響應
我認為這是后台任務的一個很好的用例。
async def remove_file(file_name):
os.remove(file_name)
@app.route('/getFiles', methods=['GET'])
async def getFiles(request):
if os.path.isfile(id+'.txt'):
request.app.add_task(remove_file(id+'.txt'))
return await response.file(id+'.txt')
return response.text("Nope, no file", status=404)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.