Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: What happens when a user closes the browser while a long process is being executed?

Tags:

python

flask

The situation is the following:

I have an app which uses Angularjs for the front-end and Flask for the back-end.

And I have a route that looks like:

@app.route('/api/route1', methods=['POST'])
def route1():
    result = some_package.long_task()
    result2 = some_package.short_task(result)
    return jsonify(result)

The long_task function is executing some bash commands using check_output, using the database, reading and writing files and so on. It can take a couple of hours to get finished.

Let's say that the user gets tired of waiting and closes the browser window 10 minutes after the process started.

My questions are:

  • Will both long_task and short_task will be executed anyway?
  • Is it possible that this situation creates any memory leakage?
  • Is it possible to know that the user closed the browser at some point? (including when I try to return the response: would it be possible to know that the response wasn't delivered?)
  • Does the answer of this question depends on what server am I using? (Tornado, uWSGI...)

Thanks a lot for your answers.

like image 251
user1294122 Avatar asked Feb 04 '15 00:02

user1294122


1 Answers

  1. Will both long_task and short_task will be executed anyway?

Yes, they will. Flask doesn't know if connection closed by the client.

  1. Is it possible that this situation creates any memory leakage?

Yes, but it depends only on your code in long_task and short_task. Memory leaks can occur even if there is no connection throw. You can write to log difference between allocated memory before and after request.

  1. Is it possible to know that the user closed the browser at some point? (including when I try to return the response: would it be possible to know that the response wasn't delivered?) Does the answer of this question depends on what server am I using? (Tornado, uWSGI...)

Simple answer - no. But it can be done with some sort of hacking with streaming empty response while long_task is executed and catching exception which will be asserted if client close connection.

You can read about it here: Stop processing Flask route if request aborted

like image 74
Eugene Soldatov Avatar answered Sep 22 '22 17:09

Eugene Soldatov