$ pip install WSGIserver
import wsgiserver
server = wsgiserver.WSGIServer(
webapp, host = '127.0.0.1', port = 80
)
server.start()
server.stop() # 停止
在实际的使用中发现,使用捕获异常来捕获终止程序的键盘指令是无效的,根本不会触发异常,如下所示:
try:
server.start()
except (KeyboardInterrupt, SystemExit):
server.stop()
print('实例已停止')
经过查阅资料,可能与包本身设计缺陷有关,故不推荐使用该包。
CherryPy 是开源、悠久、成熟的 Web 服务包,含有 WSGI 服务器功能,但在 2017 年后将 WSGI 功能与其它组件抽出组成 Cheroot 包,作为 CherryPy 的前置模块。
安装 CherryPy
$ pip install cherrypy
安装 Cheroot
$ pip install cheroot
from cheroot.wsgi import Server as WSGIServer
from cheroot.wsgi import PathInfoDispatcher as WSGIPathInfoDispatcher
webapp = WSGIPathInfoDispatcher({'/': app})
server = WSGIServer(('0.0.0.0', 80), webapp, server_name = 'my_webapp')
if __name__ == '__main__':
try:
server.start()
except KeyboardInterrupt:
server.stop()