Flask ответ вызывает FileNotFoundError, даже если статус ответа равен 200 - PullRequest
0 голосов
/ 27 мая 2020

Я создаю два вложенных временных каталога. Один - сохранить копии изображений, второй - записать видео, которое представляет собой просто список воспроизведения изображений. Это выглядит так:

@app.route("/render/<filter_name>", methods=["POST"])
def render(filter_name: str):
    if request.method == "POST":
        f = request.files["file"]

        with TemporaryDirectory() as tempdir:
            in_dir = TemporaryDirectory(dir=tempdir)
            out_dir = TemporaryDirectory(dir=tempdir)

            image = Image.open(BytesIO(f.read()))

            image.save(in_dir.name + "/image.jpg", "JPEG")

            render_mp4(in_dir.name, out_dir.name, filter_name)


            filename = "image_" + filter_name + ".mp4"

            print(filename)

            fout = open(os.path.join(out_dir.name, filename), "rb")
            print('a')
            response = make_response(fout.read())
            print('b')
            response.headers.set("Content-Type", "video/mp4")
            print('c')
            response.headers.set("Content-Disposition", "attachment", filename=filename)
            print('d')
            return response

К сожалению кажется, что TemporartDirectory закрывается быстрее, чем читается видео из-за (обратите внимание, что при возврате ответа возникает ошибка):

image_dolly-zoom-in.mp4
a
b
c
d
Exception ignored in: <finalize object at 0x7f65451299b0; dead>
Traceback (most recent call last):
  File "/home/mat/miniconda3/envs/3DPhotoCreator/lib/python3.7/weakref.py", line 572, in __call__
    return info.func(*info.args, **(info.kwargs or {}))
  File "/home/mat/miniconda3/envs/3DPhotoCreator/lib/python3.7/tempfile.py", line 797, in _cleanup
    _shutil.rmtree(name)
  File "/home/mat/miniconda3/envs/3DPhotoCreator/lib/python3.7/shutil.py", line 485, in rmtree
    onerror(os.lstat, path, sys.exc_info())
  File "/home/mat/miniconda3/envs/3DPhotoCreator/lib/python3.7/shutil.py", line 483, in rmtree
    orig_st = os.lstat(path)
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmphsvqbaan/tmpu22u108j'
Exception ignored in: <finalize object at 0x7f65451299c0; dead>
Traceback (most recent call last):
  File "/home/mat/miniconda3/envs/3DPhotoCreator/lib/python3.7/weakref.py", line 572, in __call__
    return info.func(*info.args, **(info.kwargs or {}))
  File "/home/mat/miniconda3/envs/3DPhotoCreator/lib/python3.7/tempfile.py", line 797, in _cleanup
    _shutil.rmtree(name)
  File "/home/mat/miniconda3/envs/3DPhotoCreator/lib/python3.7/shutil.py", line 485, in rmtree
    onerror(os.lstat, path, sys.exc_info())
  File "/home/mat/miniconda3/envs/3DPhotoCreator/lib/python3.7/shutil.py", line 483, in rmtree
    orig_st = os.lstat(path)
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmphsvqbaan/tmp7soqxsdg'
127.0.0.1 - - [27/May/2020 12:23:04] "POST /render/dolly-zoom-in HTTP/1.1" 200 -

Любые советы на этом?

Спасибо!

РЕДАКТИРОВАТЬ Исправлено с помощью mkdtepm ()

@app.route("/render/<filter_name>", methods=["POST"])
def render(filter_name: str):
    if request.method == "POST":
        f = request.files["file"]

        tempdir = tempfile.mkdtemp()
        in_dir = tempfile.mkdtemp(prefix="image_", dir=tempdir)
        out_dir = tempfile.mkdtemp(prefix="image_", dir=tempdir)

        image = Image.open(BytesIO(f.read()))
        image.save(in_dir.name + "/image.jpg", "JPEG")

        render_mp4(in_dir.name, out_dir.name, filter_name)

        filename = "image_" + filter_name + ".mp4"
        fout = open(os.path.join(out_dir.name, filename), "rb")

        response = make_response(fout.read())
        response.headers.set("Content-Type", "video/mp4")
        response.headers.set("Content-Disposition", "attachment", filename=filename)
        shutil.rmtree(tempdir)

        return response
...