Download a file from a Flask-based Python server

Alexandre D. picture Alexandre D. · Jun 21, 2016 · Viewed 30.9k times · Source

I'm trying to make work a code that I found at this URL: http://code.runnable.com/UiIdhKohv5JQAAB6/how-to-download-a-file-generated-on-the-fly-in-flask-for-python

My goal is to be able to download a file on a web browser when the user access to a web service on my Flask-base Python server.

So I wrote the following code:

@app.route("/api/downloadlogfile/<path>")
def DownloadLogFile (path = None):
    if path is None:
        self.Error(400)

    try:
        with open(path, 'r') as f:
            response  = make_response(f.read())
        response.headers["Content-Disposition"] = "attachment; filename=%s" % path.split("/")[2]

        return response
    except Exception as e:
        self.log.exception(e)
        self.Error(400)

But this code doesn't seem to work. Indeed I get an error that I didn't manage to fix:

Traceback (most recent call last):
File "C:\Python27\lib\site-packages\gevent\pywsgi.py", line 508, in handle_one_response
self.run_application()
File "C:\Python27\lib\site-packages\geventwebsocket\handler.py", line 88, in run_application
return super(WebSocketHandler, self).run_application()
File "C:\Python27\lib\site-packages\gevent\pywsgi.py", line 495, in run_application
self.process_result()
File "C:\Python27\lib\site-packages\gevent\pywsgi.py", line 484, in process_result
for data in self.result:
File "C:\Python27\lib\site-packages\werkzeug\wsgi.py", line 703, in __next__
return self._next()
File "C:\Python27\lib\site-packages\werkzeug\wrappers.py", line 81, in _iter_encoded
for item in iterable:
TypeError: 'Response' object is not iterable

I update my Flask and Werkzeug package to the last version but without success.

If anybody have an idea it would be great.

Thanks in advance

Answer

K DawG picture K DawG · Jun 21, 2016

The best way to solve this issue is to use the already predefined helper function send_file() in flask:

@app.route("/api/downloadlogfile/<path>")
def DownloadLogFile (path = None):
    if path is None:
        self.Error(400)
    try:
        return send_file(path, as_attachment=True)
    except Exception as e:
        self.log.exception(e)
        self.Error(400)