通过 send_file 发送文件后,如何删除 Sinatra 中的文件?
我有一个简单的 sinatra 应用程序,需要生成一个文件(通过外部进程),将该文件发送到浏览器,最后从文件系统中删除该文件。大致思路如下:
class MyApp < Sinatra::Base
get '/generate-file' do
# calls out to an external process,
# and returns the path to the generated file
file_path = generate_the_file()
# send the file to the browser
send_file(file_path)
# remove the generated file, so we don't
# completely fill up the filesystem.
File.delete(file_path)
# File.delete is never called.
end
end
但是,似乎 send_file
调用完成了请求,并且其后的任何代码都不会运行。
有什么方法可以确保生成的文件在成功发送到浏览器后被清理吗?或者我是否需要使用 cron 作业在某个时间间隔运行清理脚本?
I have a simple sinatra application that needs to generate a file (via an external process), send that file to the browser, and finally, delete the file from the filesystem. Something along these lines:
class MyApp < Sinatra::Base
get '/generate-file' do
# calls out to an external process,
# and returns the path to the generated file
file_path = generate_the_file()
# send the file to the browser
send_file(file_path)
# remove the generated file, so we don't
# completely fill up the filesystem.
File.delete(file_path)
# File.delete is never called.
end
end
It seems, however, that the send_file
call completes the request, and any code after it does not get run.
Is there some way to ensure that the generated file is cleaned up after it has been successfully sent to the browser? Or will I need to resort to a cron job running a cleanup script on some interval?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不幸的是,当您使用 send_file 时没有任何回调。这里常见的解决方案是使用 cron 任务来清理临时文件
Unfortunately there is no any callbacks when you use send_file. Common solution here is to use cron tasks to clean temp files
这可能是暂时将文件内容存储在变量中的解决方案,例如:
之后,删除文件:
最后返回内容:
这与您的
send_file()
具有相同的效果。It could be a solution to temporarily store the contents of the file in a variable, like:
After this, delete the file:
Finally, return the contents:
This has the same effect as your
send_file()
.send_file 正在流式传输文件,它不是同步调用,因此您可能无法捕获它的结尾来清理文件。我建议将它用于静态文件或非常大的文件。对于大文件,您需要一个 cron 作业或其他一些解决方案来稍后清理。您不能用相同的方法执行此操作,因为当执行仍在 get 方法中时,send_file 不会终止。如果您并不真正关心流部分,则可以使用同步选项。
当然,如果您没有对文件做任何花哨的事情,您可以坚持使用 Jochem 的答案,它完全消除了开始-确保-结束。
send_file is streaming the file, it is not a synchronous call, so you may not be able to catch the end of it to the cleanup the file. I suggest using it for static files or really big files. For the big files, you'll need a cron job or some other solution to cleanup later. You can't do it in the same method because send_file will not terminate while the execution is still in the get method. If you don't really care about the streaming part, you may use the synchronous option.
Of course, if you're not doing anything fancy with the file, you may stick with Jochem's answer which eliminate begin-ensure-end altogether.