Search code examples
pythonexceptiontracebackbasehttpserver

Python BaseHTTPServer - prevent errors ("connection reset by peer," etc.) from ruining curses display


I have a Python script that implements a built-in web server:

class http_server(BaseHTTPRequestHandler):
    def log_message(self, format, *args):
      # prevent the BaseHTTPServer log messages, we use our own logging instead
      return
    def do_GET(self):
      log("responding to http request from %s: %s" % (self.client_address[0], self.path))
      text_string = "Hello World"
      self.send_response(200)
      self.send_header("Content-type", "text/plain")
      self.send_header("Content-Length", len(text_string))
      self.end_headers()
      self.wfile.write(text_string)

def start_server():
  try:
    httpd = SocketServer.TCPServer(("", 8888), http_server)
    httpd.serve_forever()
  except Exception as e:
      cleanup(None, None)
      print "Error starting internal http server: %s" % repr(e)
      sys.exit(1)

# main script
# does various things, initializes curses, etc.
start_server()

This works fine, however the problem is that the python script also implements an on-screen status display using curses running in another thread. When an error occurs in the HTTP server (e.g. "connection reset by peer", etc.) the python traceback indicating said error gets splattered across my nice curses display.

I have tried adding try...exception blocks around the do_GET portion of my BaseHTTPRequestHandler class but that had no effect.

How can I silence Python traceback messages in this code?


Solution

  • Try overriding the handle_error method of BaseServer:

    class MyServer(SocketServer.TCPServer):
    
        def handle_error(self, request, client_address):
            pass
    

    Then use MyServer in your start_server function.