Python Flask应用程序未随系统退出而退出 [英] Python Flask app not exiting with sys exit

查看:131
本文介绍了Python Flask应用程序未随系统退出而退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够通过这样的http请求远程终止我的flask应用程序:

I'd like to be able to terminate my flask app remotely with an http request like this:

import flask
import sys

master = flask.Flask(__name__)

@master.route('/shutdown')
def shutdown():
    #do things
    sys.exit()

if __name__ == '__main__':
    master.run()

事情是行不通的.从终端我什么也没收到,好像它甚至没有处理请求一样.我知道sys.exit()只会引发SystemExit,所以我认为可能是它被某个地方捕获了.os._exit(0)确实起作用的事实也使我也这样认为.

Thing is it just doesn't work. From the terminal I get nothing, as if it's not even processing the request. I know that sys.exit() just raises a SystemExit, so I think it may be that it gets caught somewhere. The fact that os._exit(0) does work also leads me to think so.

我绊倒了一些愚蠢的东西吗?它实际上是一个错误,并且有一种解决方法吗?如果可能的话,我不希望使用os._exit(0).谢谢!

Am I tripping on something stupid? Is it actually a bug and there is a workaround? I'd prefer not to use os._exit(0) if possible. Thanks!

我不会说这个问题是重复的,因为公认的答案有所不同,另一个是13年以来的(与此同时,弗拉斯克走了很长一段路)

I wouldn't say this question is a duplicate since the accepted answers differ and the other one is from '13 (Flask's gone a long way in the meantime)

推荐答案

我认为没有错误.

烧瓶可能正在捕获所有异常,以便不停止主进程为应用程序提供服务.

As flask is probably catching all exceptions in order to do not stop the main process from serving the application.

正如您提到的,使用os._exit(0)即可完成工作.

As you mention, using os._exit(0) does the work.

据我所知,它被python2.7/SocketServer.py捕获:

As far as I've seen, it's catched by python2.7/SocketServer.py:

598         try:
599             self.finish_request(request, client_address)
600             self.shutdown_request(request)
601         except:
602             self.handle_error(request, client_address)
603             self.shutdown_request(request)

基本上可以捕获所有内容,但可以处理错误.

Which basically catches everything but handles an error.

顺便说一句:我是唯一一个认为可以通过try/except/finally进行重构的人吗?

BTW: Am I the only one who thinks that this could be refactored with a try/except/finally?

这篇关于Python Flask应用程序未随系统退出而退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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