In python using Flask, how can I write out an object for download?

前端 未结 1 1846
南旧
南旧 2020-12-12 16:33

I\'m using Flask and running foreman. I data that I\'ve constructed in memory and I want the user to be able to download this data in a text file. I don\'t want write out th

相关标签:
1条回答
  • 2020-12-12 17:01

    Streaming files to the client without saving them to disk is covered in the "pattern" section of Flask's docs - specifically, in the section on streaming. Basically, what you do is return a fully-fledged Response object wrapping your iterator:

    from flask import Response
    
    # construct your app
    
    @app.route("/get-file")
    def get_file():
        results = generate_file_data()
        generator = (cell for row in results
                        for cell in row)
    
        return Response(generator,
                           mimetype="text/plain",
                           headers={"Content-Disposition":
                                        "attachment;filename=test.txt"})
    
    0 讨论(0)
提交回复
热议问题