My view function.
from flask import Flask
from config import Config
app = Flask(__name__)
UPLOAD_FOLDER = 'filepath'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/uploader', methods=['GET', 'POST'])
@login_required
def uploader():
f = request.files['file']
if not f:
return "No file"
stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None)
file = pd.read_csv(stream)
return render_template("uploader.html", data=file.to_html())
The index HTML page for uploading where I add the form code(index.html).
<form action = "/uploader" method = "POST"
enctype = "multipart/form-data">
<input type = "file" name = "file" />
<br>
<input type = "submit"/>
</form>
And this is where I am able to see the uploaded CSV in HTML (uploader.html). Here, I want to add an additional functional where if the user clicks on the link, he'll be able to download the file as excel. How to send the data received on this HTML page to a new function called downloader which will do the functionality of downloading it as excel file.
{% extends "base.html" %}
{% block content %}
<p><a href= "{{ url_for('downloader') }}">Click to download CSV as Excel</a></p>
{{ data | safe }}
{% endblock %}
I've yet to build the downloader function but it will look something like this.
@app.route("/downloader", methods=['GET', 'POST'])
@login_required
def downloader():
....
"will receive data in some variable which I will store to df_new"
...
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
df_new.to_excel(writer, sheet_name='Sheet1')
writer.save()
output.seek(0)
return send_file(output, attachment_filename='output.xlsx', as_attachment=True)
question from:
https://stackoverflow.com/questions/65951566/how-to-pass-data-from-html-page-to-flask-function-using-which-i-want-to-download 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…