0

I am trying to generate a pdf file download with flask, this is my code:

@app.route('/return-files/')
def return_files_tut():
    from flask import send_file
    with open(os.path.join(app.config['FACTURAS_FOLDER'],'Transferencia_a_otras_cuentas_1.pdf'), 'rb') as static_file:
        return send_file(static_file, attachment_filename='file.pdf')



    

But I have the following drawback

[2021-06-21 23:34:44 +0000] [12] [ERROR] Error handling request /return-files/
plan-management       | Traceback (most recent call last):
plan-management       |   File "/usr/local/lib/python3.9/site-packages/gunicorn/workers/sync.py", line 136, in handle
plan-management       |     self.handle_request(listener, req, client, addr)
plan-management       |   File "/usr/local/lib/python3.9/site-packages/gunicorn/workers/sync.py", line 182, in handle_request
plan-management       |     resp.write_file(respiter)
plan-management       |   File "/usr/local/lib/python3.9/site-packages/gunicorn/http/wsgi.py", line 385, in write_file
plan-management       |     if not self.sendfile(respiter):
plan-management       |   File "/usr/local/lib/python3.9/site-packages/gunicorn/http/wsgi.py", line 355, in sendfile
plan-management       |     if not util.has_fileno(respiter.filelike):
plan-management       |   File "/usr/local/lib/python3.9/site-packages/gunicorn/util.py", line 574, in has_fileno
plan-management       |     obj.fileno()
plan-management       | ValueError: I/O operation on closed file

1 Answers1

2

No need to actually open the file, you can just send the file itself directly...

Note that this code is untested but it should work

Also, I would not put the import inside the function itself as it will import each time the function is executed.

from flask import send_file


@app.route('/return-files/')
def return_files_tut():
    filename = os.path.join(app.config['FACTURAS_FOLDER'],'Transferencia_a_otras_cuentas_1.pdf')
    return send_file(filename, attachment_filename='file.pdf', as_attachment=True)
Edo Akse
  • 4,051
  • 2
  • 10
  • 21