matthew fabrie
matthew fabrie

Reputation: 103

Flask send_file not opening a file

hello I am new to flask and i have to generate a pdf file and then send it to the client side with send_file(). The problem is that the flash function is executed but the send_file function is not opening the file that I am trying to send. This is my code:

def print_file_pdf(printer, file_content, options, html):
    with tempfile.NamedTemporaryFile() as f:
        f.write(file_content)
        f.flush()
        flash("Fichier PDF généré", category="success")
    return send_file("file.pdf", mimetype='image/pdf', conditional=True)

I am completely new to this so sorry if I made a stupid mistake that will trigger you :-)

Upvotes: 2

Views: 1864

Answers (1)

scotty3785
scotty3785

Reputation: 7006

As I've mentioned in my comments, your use of NamedTemporaryFile (a new thing to me) is likely the major problem here. By default NamedTemporaryFile created files are deleted straight away once you close the file.

You can change this default behaviour using delete=False as a keyword argument to NamedTemporaryFile.

Also if you want to send the file created, you need to pass that file's path to the send_file function. Get the name by accessing the f.name attribute before you leave the with context manager.

Obviously I can't test your code as you have only shared a small snippet but the following should work.

def print_file_pdf(printer, file_content, options, html):
    with tempfile.NamedTemporaryFile(delete=False) as f:
        f.write(file_content)
        f.flush()
        flash("Fichier PDF généré", category="success")
        name = f.name
    return send_file(f.name, mimetype='image/pdf', conditional=True)

Alternatively, send_file can take a "file-like object" so try

def print_file_pdf(printer, file_content, options, html):
    with tempfile.NamedTemporaryFile(delete=False) as f:
        f.write(file_content)
        f.flush()
        flash("Fichier PDF généré", category="success")
        return send_file(f, mimetype='image/pdf', conditional=True)

Upvotes: 2

Related Questions