title: Better way to port Java into Python?
body: <p>After several hours of working on porting this program over, it appears to finally be in a working state. However, I was wondering if anyone knew of a better way or more complete way of porting Java servlets over into Python. The beginning of the Python script contains a lot of support code to make it easier to port the program line-by-line directly into Python. Does anyone know of a better way to go about this?</p>
  
  <hr>
  
  <p><strong>Java</strong></p>
  
  <pre><code>// --------------------------------------------------------
  // File: Hello.java
  // Description: A simple "Hello World" servlet
  // --------------------------------------------------------
  
  import javax.servlet.*;
  import javax.servlet.http.*;
  import java.io.*;
  import java.util.*;
  import sun.servlet.http.HttpServer;
  
  public class Hello extends HttpServlet {
  
    int count;
  
    public void service(HttpServletRequest request, 
           HttpServletResponse response) throws ServletException, IOException {
  
      // setup response
  
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
  
      // send response
  
      out.println("&lt;html&gt;&lt;body&gt;");
      out.println("&lt;h5&gt;Stephen Paul Chappell (SPC)&lt;/h5&gt;");
      out.println("&lt;h5&gt;:) (ZTD) Zero The Dragon :(&lt;/h5&gt;");
      String name = request.getParameter("NAME");
      if (name != null &amp;&amp; !name.equals("")) {
        out.println("&lt;h2&gt;Hello, " + name + "&lt;/h2&gt;");
      } else {
        out.println();
        if (name != null &amp;&amp; name.equals("")) {
          out.println("  &lt;h2&gt;You didn't enter your name. Please enter your name. &lt;/h2&gt;");
        } else {
          out.println("  &lt;h2&gt;What's your name? &lt;/h2&gt;");
        }
        out.println("  &lt;hr&gt;");
        out.println("  &lt;form action=\"http://127.0.0.1:8080/servlet/Hello\"&gt;");
        out.println();
        out.println("    Enter your name: &lt;input type=\"text\" name=\"NAME\" value=\"Fred\"&gt;&lt;br&gt;");
        out.println("    &lt;input type=\"submit\" value=\"Click for greeting\"&gt;");
        out.println();
        out.println("  &lt;/form&gt;");
      }
      String color = request.getParameter("FAVCOLOR");
      if (color != null) {
        out.println("&lt;h2&gt;Why, " + color + " is my favorite color too!&lt;/h2&gt;");
      }
  
      count++;
      out.println("This page has been hit " + count + " time(s).");
  
      out.print("&lt;/body&gt;&lt;/html&gt;");
    }
  
    // start web server
    public static void main(String[] args) throws Exception {
      HttpServer.main(args);
    }
  }
  </code></pre>
  
  <hr>
  
  <p><strong>Python</strong></p>
  
  <pre><code>import urllib.parse
  import http.server
  import cgitb
  import sys
  import io
  
  ################################################################################
  
  class HttpServlet(http.server.BaseHTTPRequestHandler):
  
      __debug = False
  
      @staticmethod
      def debug(value):
          HttpServlet.__debug = value
  
      def do_GET(self):
          if self.path == '/favicon.ico':
              self.send_error(404)
              return
          request = HttpServletRequest(self.path)
          response = HttpServletResponse()
          try:
              self.service(request, response)
          except Exception:
              if HttpServlet.__debug:
                  self.send_response(500)
                  self.send_header('Content-type', 'text/html')
                  self.end_headers()
                  klass, value, trace = sys.exc_info()
                  html = cgitb.html((klass, value, trace.tb_next))
                  self.wfile.write(html.encode())
              else:
                  self.send_error(500)
          else:
              self.send_response(200)
              self.send_header('Content-type', response._type)
              self.end_headers()
              self.wfile.write(response._value)
  
      def service(self, request, response):
          raise NotImplementedError()
  
  ################################################################################
  
  class HttpServletRequest:
  
      def __init__(self, path):
          query = urllib.parse.urlparse(path).query
          self.__dict = urllib.parse.parse_qs(query, True)
  
      def getParameter(self, name):
          return self.__dict.get(name, [None])[0]
  
  ################################################################################
  
  class HttpServletResponse:
  
      def __init__(self):
          self.__content_type = 'text/plain'
          self.__print_writer = PrintWriter()
  
      def setContentType(self, content_type):
          self.__content_type = content_type
  
      def getWriter(self):
          return self.__print_writer
  
      @property
      def _type(self):
          return self.__content_type
  
      @property
      def _value(self):
          return self.__print_writer.getvalue().encode()
  
  ################################################################################
  
  class PrintWriter(io.StringIO):
  
      print = io.StringIO.write
  
      def println(self, string):
          self.write(string + '\r\n')
  
  ################################################################################
  
  class HttpServer(http.server.HTTPServer):
  
      @staticmethod
      def main(RequestHandlerClass, port=80):
          server = HttpServer(('', port), RequestHandlerClass)
          socket = server.socket.getsockname()
          print('Serving HTTP on', socket[0], 'port', socket[1], '...')
          try:
              server.serve_forever()
          except KeyboardInterrupt:
              print('Keyboard interrupt received: EXITING')
              server.server_close()
  
  ################################################################################
  ################################################################################
  
  ## ---------------------------------------------------------
  ## File: Hello.py
  ## Description: A simple "Hello World" servlet
  ## ---------------------------------------------------------
  
  class Hello(HttpServlet):
  
      count = 0
  
      def service(self, request, response):
  
          # Setup for a response.
          response.setContentType('text/html')
          out = response.getWriter()
  
          # Send an appropriate response.
          out.println('''\
  &lt;html&gt;
      &lt;head&gt;
          &lt;title&gt;Java to Python servlet&lt;/title&gt;
      &lt;/head&gt;
      &lt;body&gt;
          &lt;h5&gt;Stephen Paul Chappell (SPC)&lt;/h5&gt;
          &lt;h5&gt;:) (ZTD) Zero The Dragon :(&lt;/h5&gt;''')
          name = request.getParameter('NAME')
          if name:
              out.println('''\
          &lt;h2&gt;Hello, {}!&lt;/h2&gt;'''.format(name))
          else:
              if name == '':
                  out.println('''\
          &lt;h2&gt;You did not enter your name.&lt;/h2&gt;
          &lt;h3&gt;Please enter your name.&lt;/h3&gt;''')
              else:
                  out.println('''\
          &lt;h2&gt;What is your name?&lt;/h2&gt;''')
              out.println('''\
          &lt;form&gt;
              &lt;fieldset&gt;
                  &lt;legend&gt;About Yourself&lt;/legend&gt;
                  &lt;label for='NAME'&gt;Enter your name:&lt;/label&gt;
                  &lt;input id='NAME' name='NAME' type='text' value='John Doe' /&gt;
                  &lt;br /&gt;
                  &lt;input type='submit' value='Click me!' /&gt;
              &lt;/fieldset&gt;
          &lt;/form&gt;''')
          color = request.getParameter('FAVCOLOR')
          if color:
              out.println('''\
          &lt;h2&gt;Why, {} is my favorite color too!&lt;/h2&gt;'''.format(color))
  
          Hello.count += 1
          out.println('''\
          This page has been hit {} times.'''.format(Hello.count))
  
          out.print('''\
      &lt;/body&gt;
  &lt;/html&gt;''')
  
  # Start the web server.
  def main():
      HttpServlet.debug(True)
      HttpServer.main(Hello)
  
  ################################################################################
  
  if __name__ == '__main__':
      main()
  </code></pre>
  
  <hr>
  
  <p>In case anyone is wondering what the purpose of this project is, the original Java program was given as an introductory exercise in freshman-level computer-science course. Since then, it has been about six years since I have worked with Java and am going through the old programs, porting them over to Python for the challenge and learning experience. Porting the servlets are presenting extra difficulties.</p>