Sending a word document without saving it on the flask server

Question:

Good day. Today I’m trying to send a document generated on the server to the user on the click of a button using Flask.

My task is this:
Create a document (without saving it on the server). And send it to the user.
However, using a java script, I track the button click on the form and use fetch to make a request to the server. The server retrieves the necessary data and creates a Word document based on it. How can I form a response to a request so that the file starts downloading?

Code since the creation of the document. (The text of the Word document has been replaced)
python Falsk:

document = Document()
document.add_heading("Some head-title")
document.add_paragraph('Some text')
f = BytesIO()
document.save(f)
f.seek(0)
return send_file(f, as_attachment=True, download_name='some.docx')

However, the file does not start downloading.

How can I send a file from the server to the user?

Edits

This is my js request.

fetch('/getData', {
    method : 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        someData: someData,
    })
})
.then(response => 
    response.text()
)
.then(response =>{
    console.log(response);
});

This is my html

<form action="" name="getData" method="post" enctype="multipart/form-data">
<button type = "submit" name = "Download">Download</button>
</form>
Asked By: Sherlock_201

||

Answers:

You need to specify the mimetype, It tries to detect the mimetype from the filename but since we are not saving it we need to specify the mimetype.

return send_file(f, mimetype='application/msword', as_attachment=True, download_name='output.doc')

Answered By: darth baba
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.