如果请求中止,停止处理Flask路由 [英] Stop processing Flask route if request aborted

查看:803
本文介绍了如果请求中止,停止处理Flask路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个REST端点,它执行一些cpu密集型图像处理,并且需要几秒钟才能返回。通常,这个端点被调用,然后被客户端中止。在这些情况下,我想取消处理。

在node.js中,我会这样做:

<$ p $ ('close',function(){
//一些处理程序
});

我期待的是类似的东西,或者一个同步的方法(request.isClosed())我可以检查在我的处理过程中的某些点,如果它被关闭,返回,但我找不到。



我想发送一些东西来测试,连接仍然打开,并捕捉异常,如果失败,但似乎Flask缓冲所有输出,所以这个异常不会抛出,直到处理完成,并试图返回结果:


已建立的连接被主机中的软件中止

如何取消处理过程通过如果客户端中止他们的请求?

解决方案

有一个潜在的...哈克解决您的问题。 Flask能够通过生成器将内容流式传输给用户。 hacky部分将流式处理空白数据作为检查,看看连接是否仍然打开,然后当你的内容完成时,发生器可以产生实际的图像。您的生成器可以检查处理是否完成,并返回 None 或其他任何未完成的处理。

  from flask import回应

@ app.route('/ image')
def generate_large_image():
def generate():
while:
如果不是processing_finished():
yield
else:
yield get_image ()
return Response(generate(),mimetype ='image / jpeg')

如果客户关闭连接,我不知道你会得到什么异常,但是我敢打赌它的错误:[Errno 32] Broken pipe


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?

In node.js, I would do something like:

req.on('close', function(){
  //some handler
});

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.

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:

An established connection was aborted by the software in your host machine

How can I cancel my processing half way through if the client aborts their request?

解决方案

There is a potentially... hacky solution to your problem. Flask has the ability to stream content back to the user via a generator. The hacky part would be streaming blank data as a check to see if the connection is still open and then when your content is finished the generator could produce the actual image. Your generator could check to see if processing is done and return None or "" or whatever if it's not finished.

from flask import Response

@app.route('/image')
def generate_large_image():
    def generate():
        while True:
            if not processing_finished():
                yield ""
            else:
                yield get_image()
    return Response(generate(), mimetype='image/jpeg')

I don't know what exception you'll get if the client closes the connection but I'm willing to bet its error: [Errno 32] Broken pipe

这篇关于如果请求中止,停止处理Flask路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆