How to Embed a Web Server in Your Python3 App


This is not the first time that I created a Python3 application that spat out some output and required access to it via an HTTP server.

While there are numerous ways to achieve this, a really simple way is to embed an HTTP server directly in your Python3 application, and have it serve your output directly when called.

A sample web server in Python

from http.server import HTTPServer, BaseHTTPRequestHandler


class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        # Add additional output here
        self.wfile.write(b'Hello, world!')


httpd = HTTPServer(('', 8000), SimpleHTTPRequestHandler)
httpd.serve_forever()