I’m kind of new to Flask and I need some help. I creating a Flask where the user uploads a file, which will then be processed. The process takes about 1 to 2 minutes, but during this processing time, I want to render a “loading” HTML, which will be replaced by the Results.html ones the process is done. I thought I could make this work with jQuery (My JS knowledge is very limited). I referenced this question but for some reason, it doesn’t work. If someone could possibly help me, it would be appreciated.
python (simplyfied):
th = Thread()
finished = False
@app.route("/<jobid>/", methods=["GET"])
def upload_complete(jobid):
#code I can’t show
global th
global finished
finished = False
th = threading.Thread(target=test_thread, args=[6])
th.start()
return render_template("loading.html", jobid=jobid)
def test_thread(sec):
global finished
print ("starting")
time.sleep(sec)
print ("finished")
finished = True
@app.route('/result')
def result():
return 'Done'
@app.route('/status')
def thread_status():
return jsonify(dict(status=('finished' if finished else 'running')))
loading.html:
{% extends "templates/base.html" %}
{% block script %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
var refresh_id = setInterval(function () {
$.get(
"{{ url_for('thread_status') }}",
function (data) {
console.log(data);
if (data.status == 'finished') {
window.location.replace("{{ url_for('result') }}");
}
}
)
}
, 1000);
});
</script>
{% endblock %}
{% block title %}
succesfull upload
{% endblock %}
{% block main %}
<h1>loading</h1>
{% endblock %}
The threads works fine and the loading HTML is rendered only the result page isn’t displayed once the thread is done. I don’t know where or not this is important but the results in my terminal is the following:
127.0.0.1 - - [16/Dec/2020 14:53:08] "POST /upload/ HTTP/1.1" 302 -
starting
127.0.0.1 - - [16/Dec/2020 14:53:08] "GET /55953bfc-0795-4b4d-8d7b-a38afd2edbd5/ HTTP/1.1" 200 -
127.0.0.1 - - [16/Dec/2020 14:53:08] "GET /favicon.ico/ HTTP/1.1" 200 -
finished