Deploy Flask app as windows service Deploy Flask app as windows service windows windows

Deploy Flask app as windows service


I can't access WSGIRequestHandler in Flask outside request, so I use Process.

import win32serviceutilimport win32serviceimport win32eventimport servicemanagerfrom multiprocessing import Processfrom app import appclass 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)


Figured it out--I'd left the debug option on in the app.run(). Once i removed that, it's good to go!

While the service starts and runs correctly (I can access my flask app from another computer on the network), it is unable to stop. In the thread with the posted template i used, the author mentions something about setting a flag to properly stop the service.

Anyone know what he means by this and how to code it to properly stop the service?


I appended my code in SvcStop() last line."self.ReportServiceStatus(win32service.SERVICE_STOPPED)"

In my case, It's works for stopping service.

from app import appimport win32serviceutilimport win32serviceimport win32eventimport servicemanagerimport socketclass AppServerSvc (win32serviceutil.ServiceFramework):    _svc_name_ = "Flask App"    _svc_display_name_ = "Flask App"    def __init__(self,args):        win32serviceutil.ServiceFramework.__init__(self,args)        self.hWaitStop = win32event.CreateEvent(None,0,0,None)        socket.setdefaulttimeout(60)    def SvcStop(self):        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)        win32event.SetEvent(self.hWaitStop)        # !important! to report "SERVICE_STOPPED"        self.ReportServiceStatus(win32service.SERVICE_STOPPED)    def SvcDoRun(self):        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,                              servicemanager.PYS_SERVICE_STARTED,                              (self._svc_name_,''))        self.main()    def main(self):        app.run(host = '192.168.1.6')if __name__ == '__main__':    win32serviceutil.HandleCommandLine(AppServerSvc)