Python Flask作为Windows服务 [英] Python Flask as Windows Service
问题描述
我正在尝试获取 Flask
应用程序以在Windows中作为服务运行.我已经尝试按照建议的此处,但未成功.
I am trying to get a Flask
app to run as a Service in Windows. I have already tried to implement a solution as suggested here and here without success.
我有一个只有两个文件的简单文件夹:
I have a simple folder with just two files:
Project
|
+-- myapp.py
+-- win32_service.py
myapp.py 内部是一个简单的 Flask
应用程序:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
和服务框架 win32_service.py :
And the service skeleton win32_service.py:
import win32serviceutil
import win32service
import win32event
import win32evtlogutil
import servicemanager
import socket
import time
import logging
import os
import sys
sys.path.append(os.path.dirname(__name__))
from myapp import app
logging.basicConfig(
filename = r'c:\tmp\flask-service.log',
level = logging.DEBUG,
format = '[flaskapp] %(levelname)-7.7s %(message)s'
)
class HelloFlaskSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "FlaskApp"
_svc_display_name_ = "FlaskApp Service"
def __init__(self, *args):
win32serviceutil.ServiceFramework.__init__(self, *args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(5)
self.stop_requested = False
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
logging.info('Stopped service ...')
self.stop_requested = True
def SvcDoRun(self):
servicemanager.LogMsg(
servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,'')
)
self.main()
def main(self):
app.run(host="127.0.0.1", port=8000)
if __name__ == '__main__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(HelloFlaskSvc)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(HelloFlaskSvc)
然后我使用以下命令通过 pyinstaller
将其编译为 exe
文件:
I then compiled this to an exe
file via pyinstaller
using this command:
pyinstaller --onefile --hidden-import win32timezone win32_service.py
我成功地构建了已编译的 exe
.然后,我继续注册服务(使用管理员权限打开cmd):
I get the compiled exe
successfully built. I then proceed to register the service (open cmd with admin privileges):
>>> win32_service.exe install
> Installing service FlaskApp
> Service installed
然后我尝试启动它:
>>> win32_service.exe start
> Starting service FlaskApp
但是随后什么也没有发生(没有错误).另外,如果我尝试从任务管理器启动它,则会将状态更改为正在启动
,然后更改为已停止
.
But then nothing happens (no errors). Also if I try to start it from the Task Manager it changes the Status to Starting
and then to Stopped
.
这些是安装在 virtualenv 中的模块:
These are the modules installed in the virtualenv:
altgraph==0.16.1
Click==7.0
Flask==1.0.2
future==0.17.1
itsdangerous==1.1.0
Jinja2==2.10.1
macholib==1.11
MarkupSafe==1.1.1
pefile==2018.8.8
PyInstaller==3.4
pyodbc==4.0.26
pywin32==224
pywin32-ctypes==0.2.0
Werkzeug==0.15.2
系统规格:
Python - 3.6.5
OS - Windows 10
我在这里想念的是什么?任何帮助表示赞赏.
What I am missing here? Any help is appreciated.
编辑
Windows EventViewer显示错误:
Windows EventViewer shows an error:
The description for Event ID 3 from source FlaskApp cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.
If the event originated on another computer, the display information had to be saved with the event.
The following information was included with the event:
Traceback (most recent call last):
File "lib\site-packages\win32\lib\win32serviceutil.py", line 839, in SvcRun
File "win32_service.py", line 47, in SvcDoRun
File "win32_service.py", line 50, in main
File "lib\site-packages\flask\app.py", line 938, in run
File "lib\site-packages\flask\cli.py", line 629, in show_server_banner
File "lib\site-packages\click\utils.py", line 260, in echo
SystemError: <built-in method replace of str object at 0x000001E36AD465D0> returned a result with an error set
编辑2
如果我使用单个 spec
文件,则隐藏的导入找不到某些模块(这是 pyinstaller
的输出:
If I use a single spec
file, some modules are not found by the hidden import (this is the output from pyinstaller
:
4972 INFO: Analyzing hidden import 'ClickFlask'
4973 ERROR: Hidden import 'ClickFlask' not found
4974 INFO: Analyzing hidden import 'future'
4981 INFO: Analyzing hidden import 'itsdangerous'
5029 INFO: Analyzing hidden import 'Jinja2'
5030 ERROR: Hidden import 'Jinja2' not found
5030 INFO: Analyzing hidden import 'MarkupSafe'
5032 ERROR: Hidden import 'MarkupSafe' not found
5033 INFO: Analyzing hidden import 'pyodbc'
5034 INFO: Analyzing hidden import 'pywin32'
5035 ERROR: Hidden import 'pywin32' not found
5035 INFO: Analyzing hidden import 'pywin32-ctypes'
5036 ERROR: Hidden import 'pywin32-ctypes' not found
可能与此有关吗?为什么找到某些模块而其他模块却找不到?我正在使用virtualenv.
Could it have to do with this? Why are some modules found and others don't? I am using a virtualenv.
推荐答案
我进一步研究了 pyinstaller
github存储库,并解决了此问题.
I looked further into pyinstaller
github repo and solved this issue.
似乎 pyinstaller
与 Windows 10
有一些冲突,但是此问题是解决我的问题的关键.所有产生错误的模块都不相同.
It seems that pyinstaller
has some conflicts with Windows 10
, but this issue was the key to my problem. Althoug the module producing the error was not the same.
我设法通过在 lib \ site-packages \ click \ utils.py
中的 line 260
中添加 SystemError
异常来解决此问题 echo
函数.
I managed to solve it by adding a SystemError
exception at lib\site-packages\click\utils.py
, line 260
in the echo
function.
所以我改变了这个:
if message:
file.write(message)
对此:
if message:
try:
file.write(message)
except SystemError:
pass
使用以下命令重建exe文件:
Rebuilt the exe using:
pyinstaller --onefile --hidden-import win32timezone win32_service.py
安装该服务,然后正确启动.
Installed the service, and then it started correctly.
这篇关于Python Flask作为Windows服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!