title: Simple Python server to process GET and POST requests with JSON
body: <p>I'm trying to create a simple Python server in order to test my frontend. It should be able to handle GET and POST requests. The data should be always in JSON format until they are translated to HTTP request/response. A script with corresponding name should be called to handle each request.</p>
  
  <p>server.py</p>
  
  <pre><code>#!/usr/bin/env python
  
  from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
  import SocketServer
  import json
  import urlparse
  import subprocess
  
  class S(BaseHTTPRequestHandler):
      def _set_headers(self):
          self.send_response(200)
          self.send_header('Content-type', 'application/json')
          self.end_headers()
  
      def do_GET(self):
          self._set_headers()
          parsed_path = urlparse.urlparse(self.path)
          request_id = parsed_path.path
          response = subprocess.check_output(["python", request_id])
          self.wfile.write(json.dumps(response))
  
      def do_POST(self):
          self._set_headers()
          parsed_path = urlparse.urlparse(self.path)
          request_id = parsed_path.path
          response = subprocess.check_output(["python", request_id])
          self.wfile.write(json.dumps(response))
  
      def do_HEAD(self):
          self._set_headers()
  
  def run(server_class=HTTPServer, handler_class=S, port=8000):
      server_address = ('', port)
      httpd = server_class(server_address, handler_class)
      print 'Starting httpd...'
      httpd.serve_forever()
  
  if __name__ == "__main__":
      from sys import argv
  
      if len(argv) == 2:
          run(port=int(argv[1]))
      else:
          run()
  </code></pre>
  
  <p>Example of <code>testscript.py</code> for handling requests, which in this case just returns a JSON object.</p>
  
  <pre><code>#!/usr/bin/env python
  return {'4': 5, '6': 7}
  </code></pre>
  
  <p>The server should for example return <code>{'4': 5, '6': 7}</code> for a response in format <a href="http://www.domainname.com:8000/testscript" rel="noreferrer">http://www.domainname.com:8000/testscript</a>.</p>
  
  <p>My problem is that I can't figure out how to pass variables in between and I need help to make it work.</p>