【问题标题】:Flask and Web.py both hang on atexitFlask 和 Web.py 都挂在 atexit
【发布时间】:2012-06-05 14:38:46
【问题描述】:

我有这个简单的 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...”的消息。我使用python myapp.py 从 bash 提示符启动服务器。每当我按 CTRL-C 停止服务器时,什么都没有发生。我没有返回到 bash 提示符,也没有看到打印的“正在关闭...”消息。我也尝试使用 Web.py 来执行此操作,结果相同。

prolog_handler 做的事情就这么简单:

tstore = openPrologSession()
rules = ...

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

atexit.register(cleanUp)

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

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

【问题讨论】:

    标签: python flask web.py atexit


    【解决方案1】:

    这可能不是完美的答案,但我尝试将以下内容用于 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()
    

    【讨论】:

    • @John Peter Thompson Garcés:谢谢。检查这是否适合您。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2012-11-19
    • 2015-12-19
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多