I have a Flask App which starts a long function after validation a form. I added a flash message before that function but the message appears after the function has finished:
# main_app.py
app = Flask(__name__)
class NameForm(FlaskForm):
name = StringField('Email Adress', validators=[DataRequired()], default='[email protected]')
# some more fields
submit = SubmitField('Submit')
def run_my_long_task(name):
# do some computing
# save results to a file
# return a pandas dataframe with the results for plotting with bokeh
@app.route('/', methods=['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit():
name = form.name.data
# I want to display a message before the run starts
flash('Analysis started, please wait.')
# Start a time consuming analysis
run_my_long_task(name)
return render_template('index.html', form=form)
Here is my index.html which contains a container with the flash message handling:
<div class="container">
{% for message in get_flashed_messages() %}
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ message }}
</div>
{% endfor %}
{% block page_content %}{% endblock %}
The message shows up successfully but after the run_my_long_task() has finished. How to show up this message while the job is running?
Edit: So in general I just want to inform the user about the start of the analysis. Not necessarily need to be a flash message.
2 Answers 2
Instead of using the flash function on the server-side, you might want to use some javascript to achieve this:(this is just an example, so it might seem very ugly)
<script>
document.querySelector('DOMContentLoaded', () => {
document.querySelector("#youform").addEventListener('submit', () => {
const messageRef = document.querySelector("#flash-message");
messageRef.innerHTML = 'the message';
messageRef.styles.display = 'block';
})
});
</script>
<div class="alert alert-warning" id="flash-message" style="display: hidden;">
<button type="button" class="close" data-dismiss="alert">×</button>
</div>
Comments
I came up using Bootstrap’s JavaScript modal plugin, which is enough for my needs
flashfunction, please? It might be that you have returned a response in that flash function.time.sleepto allow the request to complete. Otherwise, the interpreter lock will not let the code continue.