将flask应用注册为windows服务
将flask应用注册为windows服务
前言
首先python应用注册为windows服务一般都要使用pywin32包,然后我在网上搜索了好多方法,试图将flask注册为服务,但是都以失败告终。
最终在一篇文章中得知,flask内置的方法Flask.run
不适合当服务器,flask的文档中也说了,Flask应用对象实质上是一个WSGI应用
,所以必须得有一个WSGI
服务器,我选了一个简单的独立WSGI
容器gevent
,总体来说比较简单,下面是具体操作内容。
步骤
安装依赖
三个依赖:
- flask
- gevent,作为WSGI服务器
- pywin32,python用的windows接口
至于哪个版本,我直接安装的最新版,如果有问题再说。
pip install flask gevent pywin32
使用pywin32编写服务
一个简单的测试flask应用
# app.py文件
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'hello world'
flask gevent
服务模板
根据自己的需求更改变量名,需要更改的地方我都加了中文注释
# server.py文件
import win32serviceutil
from gevent.pywsgi import WSGIServer
from app import app
class Service(win32serviceutil.ServiceFramework):
# 服务名
_svc_name_ = "flask_gevent_service_test"
# 显示服务名
_svc_display_name_ = "flask gevent service test display name"
# 描述
_svc_description_ = "flask gevent service test description"
def __init__(self, *args):
super().__init__(*args)
# host和ip绑定
self.http_server = WSGIServer(('127.0.0.1', 9854), app)
self.SvcStop = self.http_server.stop
self.SvcDoRun = self.http_server.serve_forever
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(Service)
添加环境变量
三个环境变量:
C:\Users\username\AppData\Local\Programs\Python\Python310
C:\Users\username\AppData\Local\Programs\Python\Python310\Scripts
C:\Users\username\AppData\Local\Programs\Python\Python310\Lib\site-packages\pywin32_system32
!!!注意两点!!!
- 注意环境变量要加在系统环境变量的Path中,不要加在用户的环境变量中!
- 上面是我的安装环境,需要根据自己python的安装路径更改环境变量,不要直接复制上去!
安装和使用
# 安装服务命令
python server.py install
# 更新服务
python server.py update
上面两个常用的就行,其他的我贴在下面
Usage: 'service.py [options] install|update|remove|start [...]|stop|restart [...]|debug [...]'
Options for 'install' and 'update' commands only:
--username domain\username : The Username the service is to run under
--password password : The password for the username
--startup [manual|auto|disabled|delayed] : How the service starts, default = manual
--interactive : Allow the service to interact with the desktop.
--perfmonini file: .ini file to use for registering performance monitor data
--perfmondll file: .dll file to use when querying the service for
performance data, default = perfmondata.dll
Options for 'start' and 'stop' commands only:
--wait seconds: Wait for the service to actually start or stop.
If you specify --wait with the 'stop' option, the service
and all dependent services will be stopped, each waiting
the specified period.
然后在系统服务中找到它,看需求设置启动方式,要想开机自启选自动就行
先启动一下,打开浏览器测试
不错
如有问题,欢迎交流!