使用专用服务器类的 Bottle HTTP 服务器 - 最小示例

此脚本使用专用类 MyServer 来适当地封装 bottle 服务器。与我们之前的文章Python bottle 最小示例相比,它以稍微多几行代码为代价提供了更好的服务器封装。

bottle_server_class.py
#!/usr/bin/env python3
from bottle import Bottle, run

class MyServer(object):
    def __init__(self):
        self.app = Bottle()
        self.init_routes()

    def init_routes(self):
        """初始化所有路由"""
        @self.app.route('/hello')
        def hello():
            return "Hello World!"

    def run(self):
        run(self.app, host='0.0.0.0', port=8080)

# 示例用法
if __name__ == "__main__":
    server = MyServer()
    server.run()

如何使用

运行服务器

run_bottle_server.sh
python bottle-server.py

并打开

example.txt
http://localhost:8080/hello

现在你应该看到 Hello World! 消息。


Check out similar posts by category: Python