I am using a Flask Code with the following route:
@app.route(\'/download\')
def download_file():
path = \"certificate.docx\"
print(\"certificate printed\
I am assuming you want the print statements to show in your HTML. I apologize if that is not what you are looking for.
First what print is doing in your example is outputting text on the server, so the text never is sent to your HTML.
To send messages to your HTML you can import flash
from flask. The flash
function will send a message to your HTML where you can receive code with get_flashed_messages()
.
Here is an example adapted from the Flask Docs.
Below we do a few things.
print
, we use flash
. The first argument passed to flash
is the message. ("certificate printed"
or os.getcwd()
) The second argument is the category of message. ( "download_file"
) Note that the category can be completely arbitrary as long as the same category is used in the template.get_flashed_messages
and assign it to a variable download_msgs
. The only argument in this case is category_filter=["download_file"]
. This will get all the messages we sent with flash
earlier and keep only the ones with the "download_file"
category.{% if download_msgs %}
, loop over messages with {% for message in download_msgs %}
, and display each message.Flask:
from flask import Flask, flash, send_file
app = Flask(__name__)
@app.route('/download')
def download_file():
path = "certificate.docx"
flash("certificate printed", "download_file")
flash(os.getcwd(), "download_file")
return send_file(path, as_attachment=True)
HTML:
Download
{% with download_msgs = get_flashed_messages(category_filter=["download_file"]) %}
{% if download_msgs %}
{% for message in download_msgs %}
- {{ message }}
{% endfor %}
{% endif %}
{% endwith %}
This example is crude, but I hope it answers your question
flash
function in your flask app.get_flashed_messages
function in your HTML code.flash
in your flask app. Use the category_filter keyword argument of get_flashed_messages
in your HTML code.