Search code examples
pythonhttpserver

How to continue python script after server started?


I have a script like this:

import http.server


class JotterServer(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-Type', 'text/plain')
        self.end_headers()
        message = "Howdy"
        self.wfile.write(bytes(message, 'utf-8'))
        return


def start_server():
    print('Starting jotter server...')
    server_address = ('127.0.0.1', 8000)
    httpd = http.server.HTTPServer(server_address, JotterServer)
    httpd.serve_forever()


if __name__ == '__main__':
    start_server()
    print("hi")

The last line never gets called. How do I keep running the code after the server is started?


Solution

  • The following program will start the server in a new thread and continue with the main thread. The main thread will print hi to console.

    import http.server
    import threading
    
    class JotterServer(http.server.BaseHTTPRequestHandler):
    
        def do_GET(self):
            self.send_response(200);
    
            self.send_header('Content-Type', 'text/plain')
            self.end_headers()
    
            message = "Howdy"
            self.wfile.write(bytes(message, 'utf-8'))
            return
    
    def start_server():
        print('Starting jotter server...')
    
        server_address = ('127.0.0.1', 8080)
        httpd = http.server.HTTPServer(server_address, JotterServer)
        thread = threading.Thread(target=httpd.serve_forever)
        thread.start()
    
    start_server()
    
    print("hi")
    

    Take special note not to put () at the end of http.server_forever since we refer to the function itself.