title: Stop processing Flask route if request aborted
body: <p>I have a flask REST endpoint that does some cpu-intensive image processing and takes a few seconds to return. Often, this endpoint gets called, then aborted by the client. In these situations I would like to cancel processing. How can I do this in flask?</p>
  
  <p>In node.js, I would do something like:</p>
  
  <pre><code>req.on('close', function(){
    //some handler
  });
  </code></pre>
  
  <p>I was expecting flask to have something similar, or a synchronous method (request.isClosed()) that I could check at certain points during my processing and return if it's closed, but I can't find one.</p>
  
  <p>I thought about sending something to test that the connection is still open, and catching the exception if it fails, but it seems Flask buffers all outputs so the exception isn't thrown until the processing completes and tries to return the result:</p>
  
  <blockquote>
    <p>An established connection was aborted by the software in your host machine</p>
  </blockquote>
  
  <p>How can I cancel my processing half way through if the client aborts their request?</p>