9

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.

user1294122
  • 323
  • 1
  • 3
  • 14

1 Answers1

5
  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

Community
  • 1
  • 1
Eugene Soldatov
  • 9,755
  • 2
  • 35
  • 43
  • Does you know where (or if) this is stated in the flask documentation? Some manual testing seems to confirm this but I'd still like to see the explanation for this behaviour. – Rowan Baker-French Oct 04 '21 at 18:31