2012-06-05 29 views
5

我有這個簡單的瓶應用:瓶和Web.py都掛在atexit對

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模​​塊與triplestore並加載一些規則啓動一個會話。它還有一個atexit函數,可以結束會話並打印一條消息,如「正在關閉...」。我使用python myapp.py從bash提示符啓動服務器。每當我按CTRL-C停止服務器時,什麼都不會發生。我不會返回到bash提示符,並且我看不到「正在打印...」消息。我也試圖用Web.py來做到這一點,並得到相同的結果。

tstore = openPrologSession() 
rules = ... 

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

atexit.register(cleanUp) 

那麼,爲什麼這麼難,只是執行的atexit任務:

的那prolog_handler確實是字面上這麼簡單? PS:如果我註釋掉所有關於打開Prolog Session並結束它的內容,並且只留下打印消息「Closing ...」的部分,那麼當我看到「Closing ...」消息時我打CTRL-C,我確實返回到bash提示符。這按預期工作。但是如果我不能對它做任何有用的事情,那又有什麼意義呢?

回答

6

這可能不是完美的答案,但我試着用以下的瓶:

# 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() 
+0

啊哈!酷男,謝謝! –

+0

@John Peter ThompsonGarcés:謝謝。檢查這是否適合你。 – pyfunc

+0

是的,它按預期工作! –