gpt4 book ai didi

python - Flask 提供文件后删除文件

转载 作者:太空宇宙 更新时间:2023-11-03 20:46:16 25 4
gpt4 key购买 nike

我有一个 Flask View ,它生成数据并使用 Pandas 将其保存为 CSV 文件,然后显示数据。第二个 View 提供生成的文件。我想在下载后删除该文件。我当前的代码引发了权限错误,可能是因为 after_request 在使用 send_from_directory 提供文件之前删除了该文件。如何在提供文件后删除该文件?

def process_data(data)
tempname = str(uuid4()) + '.csv'
data['text'].to_csv('samo/static/temp/{}'.format(tempname))
return file

@projects.route('/getcsv/<file>')
def getcsv(file):
@after_this_request
def cleanup(response):
os.remove('samo/static/temp/' + file)
return response

return send_from_directory(directory=cwd + '/samo/static/temp/', filename=file, as_attachment=True)

最佳答案

after_request 在 View 返回之后但在发送响应之前运行。发送文件可以使用流式响应;如果您在完全读取之前将其删除,您可能会遇到错误。

这主要是 Windows 上的问题,其他平台可以将文件标记为已删除并保留它,直到不再被访问为止。但是,无论平台如何,仅在确定文件已发送后才将其删除可能仍然有用。

将文件读入内存并提供服务,这样当您稍后删除它时就不会再读取它。如果文件太大而无法读入内存,请使用生成器为其提供服务,然后将其删除。

@app.route('/download_and_remove/<filename>')
def download_and_remove(filename):
path = os.path.join(current_app.instance_path, filename)

def generate():
with open(path) as f:
yield from f

os.remove(path)

r = current_app.response_class(generate(), mimetype='text/csv')
r.headers.set('Content-Disposition', 'attachment', filename='data.csv')
return r

关于python - Flask 提供文件后删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56581717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com