Running a Flask web application as a service

suggest change

This is a variation on the generic example. You just need to import your app script and invoke its run() method in the service’s main() function. In this case we’re also using the multiprocessing module due to an issue accessing WSGIRequestHandler.

import win32serviceutil
import win32service
import win32event
import servicemanager
from multiprocessing import Process

from app import app

class Service(win32serviceutil.ServiceFramework):
    _svc_name_ = "TestService"
    _svc_display_name_ = "Test Service"
    _svc_description_ = "Tests Python service framework by receiving and echoing messages over a named pipe"

    def __init__(self, *args):
        super().__init__(*args)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        self.process.terminate()
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)

    def SvcDoRun(self):
        self.process = Process(target=self.main)
        self.process.start()
        self.process.run()

    def main(self):
        app.run()

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

Process.start() runs main in a child process. Process.run() then runs it again in the service process, so this calls app.run() twice. The description still talks about a named pipe, which this script does not open. Flask and pywin32 were not installed here, and the service was not run.

Adapted from http://stackoverflow.com/a/25130524/318488

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents