如何在Flask中检测用户何时中止具有\u上下文的流\u?

2024-04-25 08:57:16 发布

您现在位置:Python中文网/ 问答频道 /正文

现在我正在提供一个带有流\u和\u上下文的文件和一个生成器。如果转到我的浏览器中的/download端点,并允许下载完成,则到达“Loop complete”print语句。但是,如果我请求下载,然后取消它(在我的浏览器中),则无法到达print语句。你知道吗

下面的代码被简化了。实际上,我正在尝试在用户完成下载或中止下载后进行数据库调用。但当用户中止下载时,就永远达不到该语句。你知道吗

@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')

Tags: 文件代码用户loop数据库getisdownload
1条回答
网友
1楼 · 发布于 2024-04-25 08:57:16

正如@jordanm所建议的,在generate函数中放置try/finally块解决了这个问题。你知道吗

示例:

@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')

相关问题 更多 >