【问题标题】:Send a file to the user, then delete file from server [duplicate]向用户发送文件,然后从服务器中删除文件[重复]
【发布时间】:2021-11-03 16:28:19
【问题描述】:

我希望我的服务器向用户发送文件,然后删除该文件。

问题是为了将文件返回给用户,我正在使用这个:

return send_file(pathAndFilename, as_attachment=True, attachment_filename = requestedFile)

既然返回了,我如何使用os.remove(pathAndFilename)从操作系统中删除文件?

我也试过这个:

send_file(pathAndFilename, as_attachment=True, attachment_filename = requestedFile)
      os.remove(pathAndFilename)
      return 0

但我得到了这个错误:

TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a int.

【问题讨论】:

    标签: python-3.x flask


    【解决方案1】:

    由于send_file已经从端点返回了响应,之后就不能再执行代码了。

    但是,可以在文件被删除之前将文件写入流,然后发送流作为响应。

    from flask import send_file
    import io, os, shutil
    
    @app.route('/download/<path:filename>')
    def download(filename):
        path = os.path.join(
            app.static_folder,
            filename
        )
        cache = io.BytesIO()
        with open(path, 'rb') as fp:
            shutil.copyfileobj(fp, cache)
            cache.flush()
        cache.seek(0)
        os.remove(path)
        return send_file(cache, as_attachment=True, attachment_filename=filename)
    

    为了实现更大的文件更好地利用内存,我觉得临时文件更适合作为缓冲区。

    from flask import send_file
    import os, shutil, tempfile
    
    @app.route('/download/<path:filename>')
    def download(filename):
        path = os.path.join(
            app.static_folder,
            filename
        )
        cache = tempfile.NamedTemporaryFile()
        with open(path, 'rb') as fp:
            shutil.copyfileobj(fp, cache)
            cache.flush()
        cache.seek(0)
        os.remove(path)
        return send_file(cache, as_attachment=True, attachment_filename=filename)
    

    我希望你的条件得到满足。
    享受实施您的项目的乐趣。

    【讨论】:

      猜你喜欢
      • 2012-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      • 1970-01-01
      相关资源
      最近更新 更多