这个场景下,在用户下载完转换好的文件再删除临时文件的最佳实际是什么?

53 天前
 drymonfidelia
from flask import Flask, request, send_file, abort
import ffmpeg
import os
import tempfile
import time

app = Flask(__name__)

@app.route('/audio_appledevices/<name>.m4a', methods=['GET'])
def convert_audio(name):
    ogg_path = f'./audio/{name}.ogg'
    if not os.path.exists(ogg_path):
        abort(404)
    with tempfile.NamedTemporaryFile(delete=False, suffix='.m4a') as temp_file:
        m4a_path = temp_file.name
    try:
        ffmpeg.input(ogg_path).output(m4a_path, codec='alac').run(overwrite_output=True)
        response = send_file(m4a_path, as_attachment=True, download_name=f'{name}.m4a', mimetype='audio/mp4')
        @response.call_on_close
        def cleanup():
            time.sleep(1)
            if os.path.exists(m4a_path):
                os.remove(m4a_path)
        return response
    except ffmpeg.Error as e:
        abort(500)


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=3389)

除非另开一个线程,不管怎么写临时文件都不能被自动删掉,要不就是 ffmpeg 写不进文件,因为临时文件被占用。 因为 ffmpeg 需要 seekable 的流,所以输出到 IO 流不可行。

请先测试再回复!我让 GPT-4 写了几十个版本,没有一个能用。

请先测试再回复!我让 GPT-4 写了几十个版本,没有一个能用。

请先测试再回复!我让 GPT-4 写了几十个版本,没有一个能用。

请先测试再回复!我让 GPT-4 写了几十个版本,没有一个能用。

2529 次点击
所在节点    Python
27 条回复
amlee
52 天前
@drymonfidelia 不会可以不要问,没必要理直气壮
tomczhen
52 天前
写了,测了,但是不想发了。( doge
tangtang369
52 天前
这样好像可以删除掉
```
from flask import Flask, request, send_file, abort,after_this_request
import ffmpeg
import os
import tempfile
import time

app = Flask(__name__)

@app.route('/audio_appledevices/<name>.m4a', methods=['GET'])
def convert_audio(name):
ogg_path = f'./audio/{name}.ogg'
if not os.path.exists(ogg_path):
abort(404)
with tempfile.NamedTemporaryFile(delete=False, suffix='.m4a') as temp_file:
m4a_path = temp_file.name
try:
ffmpeg.input(ogg_path).output(m4a_path, codec='alac').run(overwrite_output=True)
response = send_file(m4a_path, as_attachment=True, download_name=f'{name}.m4a', mimetype='audio/mp4')
print("run m4a_path",m4a_path)

@after_this_request
def cleanup(response):
print("run cleanup")
time.sleep(1)
if os.path.exists(m4a_path):
os.remove(m4a_path)
return response
return response
except ffmpeg.Error as e:
abort(500)


if __name__ == '__main__':
app.run(host='127.0.0.1', port=3389)
```
djasdjds
52 天前
@drymonfidelia #20 牛皮
drymonfidelia
52 天前
@tangtang369 还是没有删除掉,in cleanup
os.remove(m4a_path)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
tangtang369
51 天前
@drymonfidelia #25 你是 windows 吗 这个我 mac 和 linux 测了没啥问题
drymonfidelia
51 天前
@tangtang369 是的,可能是因为 Windows 的问题

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1060741

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX