2012-01-18 47 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

回答