python, cgi script for HTTP Server. Post variables are being received as None

非 Y 不嫁゛ 提交于 2019-12-08 08:30:12

问题


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.

来源:https://stackoverflow.com/questions/38024516/python-cgi-script-for-http-server-post-variables-are-being-received-as-none

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!