Uvicorn/FastAPI as a Windows service with cx_Freeze, cant stop service

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

When using cx_Freeze to create a Windows service for Uvicorn/FastAPI, the generated service might encounter issues when trying to stop it. This issue is typically caused by the way Uvicorn handles graceful shutdowns.

To address this problem, you can make use of the --force flag in the stop() method of the service script. This flag forces the termination of the service process and ensures a clean shutdown. Here's an example of how you can modify your service script to handle the issue:

python
import cx_Logging
import win32serviceutil
from uvicorn.workers import UvicornWorker

# Path to your service script generated by cx_Freeze
SERVICE_SCRIPT = r'path/to/your/service_script.py'


class UvicornService:
def __init__(self):
self.worker = None

def start(self):
cx_Logging.InitScript(logFileName='path/to/log/file.log')
self.worker = UvicornWorker('your_app:app')
self.worker.run()

def stop(self):
self.worker.should_exit = True
self.worker.force_exit = True


if __name__ == '__main__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(UvicornService)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(UvicornService)

In this modified service script, the UvicornService class now includes a stop() method that sets the should_exit and force_exit attributes of the Uvicorn worker. By setting should_exit to True and force_exit to True, the worker will be forcefully terminated, ensuring that the service stops correctly.

When stopping the service using python service_script.py stop, the stop() method will be called with the --force flag, causing the worker to exit forcefully and allowing the service to stop properly.

Remember to replace 'path/to/your/service_script.py', 'path/to/log/file.log', and 'your_app:app' with the appropriate paths and values for your specific setup.

By incorporating these modifications, you should be able to stop the Uvicorn/FastAPI service created with cx_Freeze without encountering issues.