I am trying to get a Flask Application on a Windows Server running as a service. I want to use the pywin32 package and I get to the point, where the Windows Service gets installed, but when I try to start the Service following error occurs:
The Flask Application service failed to start due to the following error: The service did not respond to the start or control request in a timely fashion.
And in another Log, I see this error:
The description for Event from source Python Service cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer. If the event originated on another computer, the display information had to be saved with the event. The following information was included with the event: ModuleNotFoundError: No module named 'servicemanager' The specified resource type cannot be found in the image file
Even when I do “pip install servicemanager”.
My run.py is a simple hello world to be sure that no source is creating these errors:
from flask import Flask
from waitress import serve
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, World!'
if __name__ == '__main__':
serve(app, host="0.0.0.0", port=3030, threads=4)
If the run.py gets started manually everything is working as expected.
The service.py:
import win32serviceutil
import win32service
import win32event
import sys
import os
from run import app
from waitress import serve
class FlaskService(win32serviceutil.ServiceFramework):
_svc_name_ = 'FlaskService'
_svc_display_name_ = 'Flask Application'
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
self.is_alive = True
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
self.is_alive = False
def SvcDoRun(self):
import logging
logging.basicConfig(
filename=os.path.join(os.getcwd(), 'service.log'),
level=logging.INFO
)
sys.stderr = sys.stdout = open(os.path.join(os.getcwd(), 'service.log'), 'a+', buffering=1)
logging.info("Service is starting")
self.main()
def main(self):
serve(app, host="0.0.0.0", port=3030, threads=4)
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(FlaskService)
What I did:
- Create the ENV
- Install all dependencies in the ENV including pywin32
- Run the service.py as administrator with activated VENV
The output looks good:
Installing service FlaskService copying host exe 'C:\Users\x\Desktop\Python \venv\lib\site-packages\win32\pythonservice.exe' -> 'C:\Users\x\Desktop\Python \venv\pythonservice.exe' Service installed
The Service is also installed but when I try to start the service, I am facing the above errors.