I have a page that uses a form with POST method that passes a file to my flask application. I have read that my app.route cannot handle both a send_file and a redirect. So my workaround is to refresh the page after the post request is successful.
Here is my HTML with my script at the bottom:
{% extends "base.html" %}
{% block head %}
<!-- {# <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/leaf.css') }}"> #} -->
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<!-- <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/base.css') }}"> -->
{% endblock %}
{% block content %}
<div id="vo_budget_file_settings">
{# <a href="/generatecleanbudgetfile" class="btn btn-primary">Upload Final CRO Budget File</a> #}
<p>Please upload the final CRO budget File</p>
<form class="" action="/generatecleanbudgetfile" method=POST enctype=multipart/form-data>
<input type="file" name="data_file" accept=".xls, .xlsx, .xlsm"/>
<input type="submit" value="Begin Format" onclick="loading();"/>
</form>
</div>
<!-- funtion to show css spinner on button click -->
<script type="text/javascript">
function loading(){
$(".loader").show();
}
</script>
<script type="text/javascript">
// Reload page 60 seconds after form submission
$("vo_budget_file_settings").onsubmit = setTimeout(function () {
window.location = "/bugetformatter";
}, 60000);
console.log(window.location);
</script>
{% endblock %}
Here is my app:
@app.route('/bugetformatter')
def data_request_portal():
return render_template('CROBudgetFormatter.html', title='CRO Budget Formatting Tool')
@app.route('/generatecleanbudgetfile', methods=['GET', 'POST'])
def clean_budget():
file = request.files.get('data_file')
app.logger.info('Conversion has started')
try:
if request.method == 'POST':
file = request.files.get('data_file')
file.seek(0)
buffer = budget_cleaner(file)
buffer.seek(0)
app.logger.info('Conversion Complete')
return send_file(
buffer,
as_attachment=True,
attachment_filename=f'stripped_budget_{dt.today().strftime("%m.%d.%Y")}.xlsx',
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
)
except:
return render_template('error_type.html', title='Unable to process uploaded budget.')
Is there a script that behaves like a callback and will only reload once the request is completed and my file downloads to the browser?