我使用 Pywin32 工具和 NSSM 为我的 Flask 应用程序创建了一个 Windows 服务。我注意到该服务不会开始给我消息:
The service did not return an error. This could be an internal Windows error or an internal service error
我注意到,当我删除对 config.json 文件(用于连接到数据库)的所有引用时,创建的服务就会启动。我的 service.py 是:
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__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(RouterService)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(RouterService)
app.py 的以下示例实现有效:
from flask import Flask
import json
import socket
app = Flask(__name__)
host = "<IP>"
user = "<username>"
passwd = "XXXXX"
DB = "YYYYY"
@app.route('/')
def hello_world():
return 'Hello, World!'
app.run(host = "0.0.0.0",debug = False, port=9000, threaded=True)
但是,只要我添加代码以从 config.json 文件读取数据库凭据,创建的服务就会给我一个错误:
conf = open('.\\config.json', "r")
data = json.loads(conf.read())
db_conf = data['db_connection']
host = db_conf['host']
user = db_conf['username']
passwd = db_conf['password']
DB = db_conf['DB']
pywin32读取json文件有什么问题吗?当我从命令提示符运行相同的 app.py 文件时,它会读取所有 json 文件并运行没有问题。