【问题标题】:Sanic Python: Delete File after sending it to a clientSanic Python:将文件发送到客户端后删除
【发布时间】:2021-02-24 14:16:04
【问题描述】:

我正在使用 Sanic 运行 Python 服务器,当客户端请求文件时,服务器会创建此文件并将其发送给客户端。目前,我一直在使用中间件: @app.listener('before_server_stop') 在服务器停止时清理这些文件。

显然,这个解决方案并不好,我希望在将响应与文件一起发送给客户端后立即清理它们。 有没有办法做到这一点?

有问题的代码:

@app.route('/getFiles', methods=['GET'])
async def getFiles(request):
        //create file
        if os.path.isfile(id+'.txt'):
            return await response.file(id+'.txt')
            // -> best would be to delete file here 

@app.listener('before_server_stop')
//delete all files

谢谢。

【问题讨论】:

    标签: python sanic


    【解决方案1】:

    您可以使用 os.remove() 删除文件

    if os.path.exists(id+'.txt'):
      os.remove(id+'.txt')
    

    您的情况的步骤:

    1- 将数据文件加载/读取到变量中

    2 - 删除文件

    3 - 返回变量内容作为 HTTP 文件响应,检查 Sanic 在 Django 中是否是这样的:

    response = HttpResponse(data, [content_type]='text/plain')
    response['Content-Disposition'] = 'attachment; filename="myfile.txt"'
    return response
    

    查看content-type/MIME-type 文件响应

    【讨论】:

    • 嗨,我已经在 before_server_stop 中执行此操作,但我想在将其发送到客户端后立即执行此操作。
    • HTTP 中的文件响应应该可以解决问题 ;)
    【解决方案2】:

    我认为这是 background tasks 的一个很好的用例。

    async def remove_file(file_name):
        os.remove(file_name)
    
    @app.route('/getFiles', methods=['GET'])
    async def getFiles(request):
        if os.path.isfile(id+'.txt'):
            request.app.add_task(remove_file(id+'.txt'))
            return await response.file(id+'.txt')
        return response.text("Nope, no file", status=404)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-15
      • 2018-10-27
      • 2013-05-23
      • 2018-06-18
      • 1970-01-01
      • 2020-07-12
      • 2015-05-02
      相关资源
      最近更新 更多