[英]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.