0

I am developing a Python and I followed the guidelines here for building a Windows Service with Flask and Pywin32.

The setup of my code is as follow:

class AppServerSvc (win32serviceutil.ServiceFramework):

_svc_name_ = "my_services"
_svc_display_name_ = "My service"

logging.basicConfig(
    filename    = 'c:\\TMP\\{}.log'.format(_svc_name_),
    level       = logging.DEBUG,
    format      = '%(levelname)-7.7s @ %(asctime)s: %(message)s'
)

def __init__(self,args):
    win32serviceutil.ServiceFramework.__init__(self,args)
    self.hWaitStop = win32event.CreateEvent(None,0,0,None)
    socket.setdefaulttimeout(60)
    try:
        self.log('START: Service start')
        self.ReportServiceStatus(win32service.SERVICE_RUNNING)
        self.start()
        win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE)
    except Exception as e:
        self.log('Exception: {}'.format(e))
        self.SvcStop()

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_,''))
    try:
        self.log('START: Service start')
        self.ReportServiceStatus(win32service.SERVICE_RUNNING)
        self.start()
        win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE)
    except Exception as e:
        self.log('Exception: {}'.format(e))
        self.SvcStop()

    self.main()

def main(self):
    app.run(host= '127.0.0.1', port= '5000')
    pass

def log(self, msg):
    servicemanager.LogInfoMsg(str(msg))  #system log
    logging.info(str(msg))               #text log    
    
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def send_html(path):
    if path == '':
        path = 'index.html'
    return send_from_directory(os.path.join(root_dir(), 'static-file'), path)

@app.route('/my_app', methods = ['POST'])
def my_application():
    
    //my app

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(AppServerSvc)

In debug all is working fine, When I try to start the service into the log file appear:

INFO    @ 2021-03-01 08:35:55,857: START: Service start
INFO    @ 2021-03-01 08:35:55,857: Exception: 'AppServerSvc' object has no attribute 'start'
John Conde
  • 217,595
  • 99
  • 455
  • 496
leonardo
  • 3
  • 2

1 Answers1

0

So, after some control on the code I found the solution:

 def start(self):
        self.runflag = True
        while self.runflag:
            win32api.Sleep((2*1000), True)
            self.log('Service alive')
 def stop(self): 
        self.runflag = False
        self.log('Stop received')

With this functions the problem is fixed.

leonardo
  • 3
  • 2