本文介绍了将 Flask 应用程序部署为 Windows 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此处找到的模板:是否可以在 Windows 中将 Python 脚本作为服务运行?如果可能,怎么做?

I'm using the template found here: Is it possible to run a Python script as a service in Windows? If possible, how?

这是我的 run.py,我已按照上述链接中的说明将其安装为服务.

Here's my run.py, which i've installed as a service following the instructions in the above link.

from app import app

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket


class AppServerSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "Flask App"
    _svc_display_name_ = "Flask App"

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

    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_,''))
        self.main()

    def main(self):
        app.run(host = '192.168.1.6')

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

但是,当我尝试启动该服务时,我收到以下消息:

However, when I try to start the service i get the message:

本地计算机上的 Flask App 服务启动然后停止.如果其他服务或程序未使用某些服务,它们会自动停止."

"The Flask App service on Local Computer started and then stopped.Some services stop automatically if they are not in use by other services or programs."

知道我做错了什么吗?我尝试了各种用户帐户——我认为这不是权限问题.

Any idea what I'm doing wrong? I have tried various user accounts--i don't think it's a permission problem.

谢谢!

推荐答案

我在request之外的Flask中无法访问WSGIRequestHandler,所以我使用Process.

I can't access WSGIRequestHandler in Flask outside request, so I use Process.

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)

这篇关于将 Flask 应用程序部署为 Windows 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 15:07