Service wrapper

Install pywin32 globally.
 
PS D:\Program Files\Python39> .\python.exe -m pip install pywin32
PS D:\Program Files\Python39> .\python.exe .\Scripts\pywin32_postinstall.py -install
Stop any other pywin32 service, if it' running (important).
 
D:\python-apps\fastapi-service>python fastapi_service.py install
D:\python-apps\fastapi-service>python fastapi_service.py start
Service wrapper.
 
""" FASTAPI SERVICE - WRAPPER

Windows PowerShell:
cd D:\python-apps\fastapi-service
.\myenv\Scripts\activate
(myenv) pip install pywin32
(myenv) D:\python-apps\fastapi-service>

Install:
python fastapi_service.py install
python fastapi_service.py start

Reinstall:
python fastapi_service.py stop
python fastapi_service.py remove
"""

import win32serviceutil
import win32service
import win32event
import servicemanager
import subprocess
import sys
import os

class FastAPIService(win32serviceutil.ServiceFramework):
    _svc_name_ = "AppPPF_FastAPIService"
    _svc_display_name_ = "AppPPF FastAPI v1.0"
    _svc_description_ = "PPF FastAPI Application Service"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.process = None

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        if self.process:
            self.process.terminate()

    def SvcDoRun(self):
        servicemanager.LogInfoMsg("Starting FastAPI...")
        # Path to your virtual environment Python
        venv_python = "D:/python-apps/fastapi-service/venv/Scripts/python.exe"
        # Path to your FastAPI app
        app_script = "D:/python-apps/fastapi-service/server.py"
        # Start FastAPI app
        self.process = subprocess.Popen([venv_python, "-B", app_script])
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

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

Migrations

 
(myenv) pip freeze > requirements.txt
(myenv) pip install -r requirements.txt