2012-01-18 37 views
2

無法找到其他類似情況已經實現的情況。在WSGI環境中啓動一個單獨的線程

我有一個用Werkzeug構建的WSGI應用程序,如果可能的話我想在與WSGI應用程序相同的上下文中運行一些後臺清理過程(我寧願在cron中沒有單獨的腳本,當應用程序作爲服務啓動的時候,必要的後臺任務也在運行。)正在使用的web服務器是mod_wsgi的Apache。

讓我們假設一個非常基本的WSGI示例,因爲所服務的內容並不真正存在。我將使用一個Pocoo具有在official Werkzeug docs:

class Shortly(object): 

    def __init__(self, config): 
     self.redis = redis.Redis(config['redis_host'], config['redis_port']) 

    def dispatch_request(self, request): 
     return Response('Hello World!') 

    def wsgi_app(self, environ, start_response): 
     request = Request(environ) 
     response = self.dispatch_request(request) 
     return response(environ, start_response) 

    def __call__(self, environ, start_response): 
     return self.wsgi_app(environ, start_response) 


def create_app(redis_host='localhost', redis_port=6379): 
    app = Shortly({ 
     'redis_host':  redis_host, 
     'redis_port':  redis_port 
    }) 
    return app 

難道是可行的啓動create_app功能,將繼續前進,在固定的時間間隔執行這些任務中執行的另一個無阻塞線程? mod_wsgi是否需要「連續運行」應用程序?

def create_app(redis_host='localhost', redis_port=6379): 
    app = Shortly({ 
     'redis_host':  redis_host, 
     'redis_port':  redis_port 
    }) 

    #do some other stuff in a separate thread while the webapp is running 
    task = threading.Thread(target=DBCleanup, args=(query, stuff)) 
    task.start() 
    return app 
+0

爲什麼WSGI應用程序不能將其作爲守護進程啓動,並在退出時將其關閉? – 2012-01-18 19:41:19

+0

@ IgnacioVazquez-Abrams難道我的回答就是讓守護神的東西嚇倒我嗎? ;)從來沒有用Python編寫過一個腳本,這個腳本是以這種方式使用的。你知道關於這個問題的任何好的引物嗎?謝謝! – DeaconDesperado 2012-01-18 19:44:26

回答

相關問題