6

我有这个简单的 Flask 应用程序:

from flask import Flask
import prolog_handler as p

app = Flask(__name__)
app.debug = False

@app.route('/')
def hello():
    for rule in p.rules:
        print rule
    return 'hello'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)

prolog_handler 模块使用三元存储启动会话并加载一些规则。它还有一个 atexit 函数,可以结束会话并打印类似“Closing...”的消息。我从 bash 提示符启动服务器python myapp.py。每当我按 CTRL-C 停止服务器时,什么都没有发生。我没有返回到 bash 提示符,也没有看到打印的“正在关闭...”消息。我也尝试使用 Web.py 来执行此操作,结果相同。

prolog_handler 所做的实际上就像这样简单:

tstore = openPrologSession()
rules = ...

def cleanUp():
    print "Closing..."
    tstore.endSession()

atexit.register(cleanUp)

那么为什么只执行一个 atexit 任务这么困难呢?

PS:如果我注释掉有关打开 Prolog 会话并结束它的所有内容,只留下打印消息“Closing ...”的部分,那么当我按下 CTRL- 时,我确实看到了“Closing ...”消息C 和我确实返回到 bash 提示符。这按预期工作。但是,如果我不能用它做任何有用的事情,那么 atexit 有什么意义呢?

4

1 回答 1

7

这可能不是完美的答案,但我尝试将以下内容用于 Flask:

# These functions should be called when you tear down the application
app.teardown_functions = []

def teardown_applications(): 
    for func in app.teardown_functions:
       print('Calling teardown function %s' % func.__name__)
        func()

app.teardown_functions.append(function_tocall_at_exit)

这似乎对我有用。我也倾向于将 gevent 用于所有烧瓶应用程序

if __name__ == '__main__':
    gevent.signal(signal.SIGINT, teardown_applications)
    http_server = WSGIServer(('', 5000), app)
    http_server.serve_forever()

这通常对我有用。

一些模块导入:

from flask import Flask
from gevent.wsgi import WSGIServer
import gevent
import signal

from gevent import monkey
monkey.patch_all()
于 2012-06-05T15:50:41.197 回答