如何将Flask/Gevent.SocketIO服务器制作成Python Windows服务?

9 投票
3 回答
4035 浏览
提问于 2025-04-17 15:48

我有一个使用flask和gevent的SocketIOServer,现在想把它做成一个服务:

class TeleportService(win32serviceutil.ServiceFramework):
    _svc_name_ = "TeleportServer"
    _svc_display_name_ = "Teleport Database Backup Service"
    _svc_description_ = "More info at www.elmalabarista.com/teleport"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, ''))

        self.ReportServiceStatus(win32service.SERVICE_RUNNING)

        runServer()


@werkzeug.serving.run_with_reloader
def runServer():
    print 'Listening on %s...' % WEB_PORT
    ws = SocketIOServer(('0.0.0.0', WEB_PORT),
        SharedDataMiddleware(app, {}),
        resource="socket.io",
        policy_server=False)

    gevent.spawn(runTaskManager).link_exception(lambda *args: sys.exit("important_greenlet died"))

    ws.serve_forever()

但是,我不知道怎么在SvcStop的时候停止它。而且它运行时有个奇怪的现象,就是服务管理器解析命令行参数是在runserver被杀掉之后进行的。这意味着flask服务器是运行着的,我可以通过网页访问,但服务管理器却显示它“没有启动”。比如,在命令行中运行:

C:\Proyectos\TeleportServer>python service.py uninstall <--BAD PARAM, TO MAKE IT OBVIOUS
2013-02-13 16:19:30,786 - DEBUG: Connecting to localhost:9097
 * Restarting with reloader
2013-02-13 16:19:32,650 - DEBUG: Connecting to localhost:9097
Listening on 5000...
Growl not available: Teleport Backup Server is started
KeyboardInterrupt <--- HERE I INTERRUPT WITH CTRL-C
Unknown command - 'uninstall'
Usage: 'service.py [options] install|update|remove|start [...]|stop|restart [...
]|debug [...]'
Options for 'install' and 'update' commands only:
 --username domain\username : The Username the service is to run under
 --password password : The password for the username
 --startup [manual|auto|disabled] : How the service starts, default = manual
 --interactive : Allow the service to interact with the desktop.
 --perfmonini file: .ini file to use for registering performance monitor data

根据建议去掉实时重载后,剩下的代码是这样的。不过,问题还是一样。

def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, ''))

#self.timeout = 640000    #640 seconds / 10 minutes (value is in milliseconds)
self.timeout = 6000     #120 seconds / 2 minutes
# This is how long the service will wait to run / refresh itself (see script below)
notify.debug("Starting service")

ws = getServer()

while 1:
    # Wait for service stop signal, if I timeout, loop again
    gevent.sleep(0)
    rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
    # Check to see if self.hWaitStop happened
    if rc == win32event.WAIT_OBJECT_0:
        # Stop signal encountered
        notify.debug("Stopping service")
        ws.kill()
        servicemanager.LogInfoMsg("TeleportService - STOPPED!")  #For Event Log
        break
    else:
        notify.debug("Starting web server")
        ws.serve_forever()

3 个回答

0

我在Flask中无法在request之外访问WSGIRequestHandler,所以我使用了Process

import win32serviceutil
import win32service
import win32event
import servicemanager
from multiprocessing import Process

from app import app


class Service(win32serviceutil.ServiceFramework):
    _svc_name_ = "TestService"
    _svc_display_name_ = "Test Service"
    _svc_description_ = "Tests Python service framework by receiving and echoing messages over a named pipe"

    def __init__(self, *args):
        super().__init__(*args)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        self.process.terminate()
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)

    def SvcDoRun(self):
        self.process = Process(target=self.main)
        self.process.start()
        self.process.run()

    def main(self):
        app.run()


if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(Service)
0

方法 serve_forever 是来自于 BaseServer.serve_forever。要停止这个方法,你需要调用 BaseServer.shutdown() 或者它的衍生方法。

简单来说,你需要在全局范围内声明 ws。把这段代码放在你的 Service 类定义之前就是一种方法。

ws = None

然后把你的 Service.SvcStop 的实现改成这样:

def SvcStop(self):
    self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)

    #Tell the serve_forever() loop to stop and wait until it does. 
    ws.shutdown()

因为 ws.shutdown() 已经会等待监听器停止,所以你可以去掉 self.hWaitStop,除非你在代码的其他地方用到了它。

需要 Python 2.6 及以上版本。

2

要阻止它从 SvcStop 停止,你需要把 "ws" 的引用存储在一个全局变量中(也就是说,放在一个可以后续取用的地方)。据我所知,调用 "ws.kill()" 应该能结束这个循环。

run_with_reloader 这个装饰器似乎会立即运行被装饰的函数,这就解释了为什么在运行网络服务器后命令行会被处理。如果你需要自动重载,显然这个装饰器只有在需要重载时才需要使用。

更新:添加了示例服务代码

在一个不使用 flask 或 gevent 的项目中,我使用类似这样的代码(省略了很多细节):

class Service (win32serviceutil.ServiceFramework):

   def __init__(self, *args, **kwds):
       self._mainloop = None
       win32serviceutil.ServiceFramework.__init__(self, *args, **kwds)

   def SvcStop(self):
       self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)

       if self._mainloop is not None:
           self._mainloop.shutdown()


    def SvcStart(self):
        self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
        self._mainloop = ... .MainLoop()
        self.ReportServiceStatus(win32service.SERVICE_RUNNING)
        try:
            self._mainloop.run_forever()

        finally:
            self.ReportServiceStatus(win32service.SERVICE_STOPPED)

win32serviceutil.HandleCommandLine(Service)

撰写回答