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

11次阅读

共计 932 个字符,预计需要花费 3 分钟才能阅读完成。

from flask import Flask, request, send_file, abort
import ffmpeg
import os
import tempfile
import time

app = Flask(__name__)

@app.route('/audio_appledevices/.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 写了几十个版本,没有一个能用。

正文完
 0