0

After researching, I know there is no way to send_file and render_template in one return; however, all of the other solutions pointed to a document that is stored on a server. Is there a workaround for a stream to send_file and load a template either in the same page or another one?

app = Flask(__name__)

@app.route('/', methods=['GET','POST'])
def homes():
    if request.method == 'POST':
        document = request.files['test']
        stream = io.BytesIO(document.read())
        doc = aw.Document(stream)
        # random doc manipulation


    return send_file(doc, as_attachment=True, download_name='test.docx')
    return render_template("index.html")
Finntech
  • 105
  • 6

1 Answers1

0

You can seperate the two routes like:

app.py

app = Flask(__name__)

@app.route('/', methods=['GET','POST'])
def homes():
    return render_template("index.html") <- post a link to the `download_file` route in this template

@app.route('/download_file', methods=['GET'])
def download_file():
    if request.method == 'GET'
        document = request.files['test']
        stream = io.BytesIO(document.read())
        doc = aw.Document(stream)

    return send_file(doc, as_attachment=True, download_name='test.docx')

Then in your html file use this:

index.html (example)

<!DOCTYPE html>
<html lang="en">
<body>
    <ul>
        <li><a href="{{ url_for('download_file') }}">Download</a>
    </ul>
</body>
</html>
SLDem
  • 2,065
  • 1
  • 8
  • 28
  • Is there a way to have this done without the file being stored on the server? It looks like your solution does `send_file` for a file on a server. In this situation, I want the user to submit the file through an upload button, then the script manipulates the document and saves to a stream, then pushes it back to the uploader. – Finntech Aug 05 '22 at 20:45
  • you would have to use the `js` for that, but you will still need at least another route in your app, preferably a route with the template and two other routes - one to upload a file to the server and process it and another to download it after it has been processed – SLDem Aug 05 '22 at 20:55
  • Is there any chance you might have seen this online with a stream? Have been spinning my wheels for weeks trying to figure this out and can't find anything from my research. – Finntech Aug 09 '22 at 13:39
  • check out this answer: https://stackoverflow.com/questions/1395807/proper-way-to-handle-multiple-forms-on-one-page-in-django – SLDem Aug 09 '22 at 14:35
  • but if you want it to dynamically update you'll have to use `js` – SLDem Aug 09 '22 at 14:36