Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
flask send_file with temporary files

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)
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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')
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!