title: How do I terminate a flask app that's running as a service?
body: <p>I was able to get my flask app running as a service thanks to <a href="https://stackoverflow.com/questions/32404/is-it-possible-to-run-a-python-script-as-a-service-in-windows-if-possible-how">Is it possible to run a Python script as a service in Windows? If possible, how?</a>, but when it comes to stopping it i cannot. I have to terminate the process in task manager. </p>
  
  <p>Here's my run.py which I turn into a service via run.py install: </p>
  
  <pre><code>from app import app
  
  from multiprocessing import Process
  import win32serviceutil
  import win32service
  import win32event
  import servicemanager
  import socket
  
  
  class AppServerSvc (win32serviceutil.ServiceFramework):
      _svc_name_ = "CCApp"
      _svc_display_name_ = "CC 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)
          server.terminate()
          server.join()
  
      def SvcDoRun(self):
          servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                                servicemanager.PYS_SERVICE_STARTED,
                                (self._svc_name_,''))
          self.main()
  
      def main(self):
          server = Process(app.run(host = '192.168.1.6'))
          server.start()
  
  if __name__ == '__main__':
      win32serviceutil.HandleCommandLine(AppServerSvc)
  </code></pre>
  
  <p>I got the process stuff from this post: <a href="http://librelist.com/browser/flask/2011/1/10/start-stop-flask/#a235e60dcaebaa1e134271e029f801fe" rel="nofollow noreferrer">http://librelist.com/browser/flask/2011/1/10/start-stop-flask/#a235e60dcaebaa1e134271e029f801fe</a> but unfortunately it doesn't work either. </p>
  
  <p>The log file in Event Viewer says that the global variable 'server' is not defined. However, i've made server a global variable and it still gives me the same error.</p>