1

I am using following cgi script written in python for running an HTTP server. Its working fine. do_POST function is being invoked on making post request. However I am not able to receive the post variables on server side. I am trying to fetch post variables by these statements(found them here):

postData = cgi.FieldStorage()
fname = postData.getvalue("fname")

when I print fname and postData. I get following output:

FieldStorage(None, None, [])
None

The full script is:

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import SocketServer
import cgi

class S(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        self.wfile.write("<html><body><h1>hi!</h1></body></html>")

    def do_HEAD(self):
        self._set_headers()

    def do_POST(self):
        self._set_headers()
        postData = cgi.FieldStorage()
        print postData
        print postData.getvalue("fname")
        self.wfile.write("<html><body><h1>POST!</h1></body></html>")

def run(server_class=HTTPServer, handler_class=S, port=80):
    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()

I have tried to make post request in following two ways.

1) curl -d "fname=bar&lname=baz" http://localhost
2) By using following HTML page:

<form action="http://localhost" method="post">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  <input type="submit" value="Submit">
</form>

In both ways the client receives the correct response, but the post variables are not accessible on server side. Any help is appreciated.

Community
  • 1
  • 1
Chor Sipahi
  • 546
  • 3
  • 10

0 Answers0