Bottle HTTP server with dedicated server class – minimal example

This script uses a dedicated class MyServer to encapsulate the bottle server appropriately. Compared to our previous post Python bottle minimal example it provides better encapsulation of the server at the cost of slightly more lines of code.

#!/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):
        """Initialize all routes"""
        @self.app.route('/hello')
        def hello():
            return "Hello World!"

    def run(self):
        run(self.app, host='0.0.0.0', port=8080)
        
# Example usage
if __name__ == "__main__":
    server = MyServer()
    server.run()

How to use

Run the server

python bottle-server.py

and open

http://localhost:8080/hello

Now you should see the Hello World! message.