Home > Mobile >  flask send_file with temporary files
flask send_file with temporary files

Time:11-08

If I remove the pdf file creation from a tempfile wrapper I am able to send a proper file, but when I wrap with tempfile I get this error:

AttributeError: 'bytes' object has no attribute 'read'

I tried to remove the .read() from my filepath but then I get another error regarding trying to read a closed file. Ive looked online at the flask send_file and it appears there is an issue with using send_file on tmp files. Does anyone have a work around? I dont want to create a file then manually remove it once it is sent, id like to keep it as a tempfile

with tempfile.TemporaryFile() as fp:
     PDF.dumps(fp, pdf)
     return send_file(fp.read(), attachment_filename="invoice" str(invoice["id"]) ".pdf", as_attachment=True)

CodePudding user response:

Using a TemporaryFile as a context manager, the file is closed as soon as the block ends. The send_file call doesn't read the file right then - it just returns an object that makes your file be read later on, after the context manager closes.

Per the tempfile documentation, files are cleaned up when the file handle is closed, and PEP 333, the WSGI spec, specifies that compliant implementations must close(), so we can do this without a context manager:

    tmp = tempfile.TemporaryFile()
    tmp.write(b'some content')
    tmp.seek(0)
    return send_file(tmp, attachment_filename='example.txt')
  • Related