-1

I am trying to return a file and changing the template in Flask.

return send_file(myfile, as_attachment=True), return render_template("template.html")

But it gives me an error. If I try to make 2 returns like this:

return send_file(myfile, as_attachment=True)
return render_template("template.html")

or

return render_template("template.html")
return send_file(myfile, as_attachment=True)

It doesn't work eitherway. How do I fix this?

Thanks

2 Answers2

1

You only get one response per request. You can either send a file, or send a new page.

Bear the above in mind by @Tim Roberts.

How do I send the file and then send the new page?.

A long possible ride I suggest you do something like this (Note you use another view for sending the file too).

    # ...
    if request.GET.get("send", None):
        return send_file(myfile, as_attachment=True)
    return render_template("template.html")

In the template use ajax to make GET request to the view

ajax.get({
    "/the-view-url/?send=file",
    success: function(data) {
    // do whatever you want with data (file)
    }

Tada !! you can now return a response or a file.

I suggest you consider this:

It seems like you need to learn Python's fundamentals. – mac13k

0

You only get one response per request. You can either send a file, or send a new page.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • How do I send the file and then send the new page? – RainbowSheep Feb 06 '22 at 21:27
  • 1
    You can use Javascript to create a download link and click on it, then do a `window.locations = ` to move to a new URL. https://stackoverflow.com/questions/1066452/easiest-way-to-open-a-download-window-without-navigating-away-from-the-page – Tim Roberts Feb 06 '22 at 21:47