Ari
Ari

Reputation: 6169

Flask - Detecting when a function has finished running and visually indicating to the user

I have a button the user can press, it calls a function and nothing can happen until the function has finished executing. Is it possible to let the user press the button, call the function, but continue using the site and when the function has returned its output let the user know.

@app.route('/run_probe', methods=['POST'])
def run_probe():
    if request.method == 'POST':
        input_directory = request.form['directory']

        if os.path.isdir(input_directory):
            files = get_file_list.probe(input_directory)
            return render_template('index.html', files=files)

        else:
            flash('Could not probe directory')
            return redirect(url_for('index'))

This lets the user enter a directory/filepath into an <input> then it scans the directory and returns a list of filepaths. But this needs to finish befor the user can go anywhere else.

It would be nice if the user could run the function and do something else and when the function is done, return some sort of notication. Or even just a visual status.

I was thinking instead of directly returning a list, send the output to a mongodb for later retrieval, but if I hit run it still needs to do os.walk() before letting me continue.

Upvotes: 1

Views: 643

Answers (1)

Victor
Victor

Reputation: 612

You may need to use Javascript for that:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
const Url="http://host:port/to/your/time/consumming_function";
$("#button").on('click', function() {
    $.ajax({
        type:'GET',
        url = Url,
        success: function(data) {
            //Update your document here or redirect
        }
    )}
    return false; //Avoid auto reloading
}
</script>

The main idea is Ajax will request your Flask app. Then it will call function in success when it will finish. At this moment, update the content or redirect the user. The user will be able to continue on the same webpage while the ajax request is still running.

I just want to prevent you that you can get a timeout error if your task is too long. You may specify a timeout.

Upvotes: 2

Related Questions