How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?

后端 未结 10 1215
渐次进展
渐次进展 2020-12-01 04:53

I am running my HTTPServer in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main

10条回答
  •  一个人的身影
    2020-12-01 05:57

    This method I use successfully (Python 3) to stop the server from the web application itself (a web page):

    import http.server
    import os
    import re
    
    class PatientHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
        stop_server = False
        base_directory = "/static/"
        # A file to use as an "server stopped user information" page.
        stop_command = "/control/stop.html"
        def send_head(self):
            self.path = os.path.normpath(self.path)
            if self.path == PatientHTTPRequestHandler.stop_command and self.address_string() == "127.0.0.1":
                # I wanted that only the local machine could stop the server.
                PatientHTTPRequestHandler.stop_server = True
                # Allow the stop page to be displayed.
                return http.server.SimpleHTTPRequestHandler.send_head(self)
            if self.path.startswith(PatientHTTPRequestHandler.base_directory):
                return http.server.SimpleHTTPRequestHandler.send_head(self)
            else:
                return self.send_error(404, "Not allowed", "The path you requested is forbidden.")
    
    if __name__ == "__main__":
        httpd = http.server.HTTPServer(("127.0.0.1", 8080), PatientHTTPRequestHandler)
        # A timeout is needed for server to check periodically for KeyboardInterrupt
        httpd.timeout = 1
        while not PatientHTTPRequestHandler.stop_server:
            httpd.handle_request()
    

    This way, pages served via base address http://localhost:8080/static/ (example http://localhost:8080/static/styles/common.css) will be served by the default handler, an access to http://localhost:8080/control/stop.html from the server's computer will display stop.html then stop the server, any other option will be forbidden.

提交回复
热议问题