1

Right now I am serving a file with stream_with_context and a generator. If go to the /download endpoint in my browser, and allow the download to complete, then the 'Loop complete' print statement is reached. However, if I request the download, then cancel it (in my browser), then the print statement is not reached.

The code below is simplified. I am actually trying to make a database call AFTER the download is completed or aborted by the user. But when the user aborts the download, the statement is never reached.

@app.route('/download', methods=['GET'])
def download():
    if request.method == 'GET':
        def generate():
            for i in range(100):
                yield i # simplified code
            print('Loop complete') # this statement is only reached when the download is completed

        return Response(stream_with_context(generate()), mimetype='video/MP2T')
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Arman
  • 655
  • 2
  • 7
  • 23

1 Answers1

0

As @jordanm suggests, placing a try/finally block in the generate function fixed the problem.

Example:

@app.route('/download', methods=['GET'])
def download():
    if request.method == 'GET':
        def generate():
            try:
                for i in range(100):
                    yield i
            finally:
                print('Complete')

        return Response(stream_with_context(generate()), mimetype='video/MP2T')
Arman
  • 655
  • 2
  • 7
  • 23