我正在尝试获取一个从http POST接收数据的基本Python网络服务器示例。我目前正在使用Postman发送http POST,如下所示:
这是我的Python脚本:
# simple_web_server.py
import SimpleHTTPServer
import SocketServer
import cgi
###################################################################################################
def main():
myRequestHandler = MyRequestHandler
socketTCPServer = SocketServer.TCPServer(('0.0.0.0', 8080), myRequestHandler)
print 'starting server, use <Ctrl-C> to stop'
socketTCPServer.serve_forever()
###################################################################################################
class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
print "in do_GET(self)"
return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
def do_POST(self):
print "in do_POST(self)" # this shows successfully to the command line
form = cgi.FieldStorage()
print cgi.print_form(form) # this always prints an empty form
print str(form.getvalue('name')) # this always prints an empty string
if "name" not in form or "addr" not in form: # the if never runs
print "Please fill in the name and addr fields."
else:
print "<p>name:", form["name"].value
print "<p>addr:", form["addr"].value
self.wfile.write("test response 123 \n") # this shows successfully in Postman
self.send_response(200) # the 200 is successfully received by Postman
###################################################################################################
if __name__ == "__main__":
main()
以下是运行时Python的命令行结果:
starting server, use <Ctrl-C> to stop
127.0.0.1 - - [05/Jul/2016 20:02:33] "POST /?param1=value1¶m2=value2 HTTP/1.1" 200 -
in do_POST(self)
<H3>Form Contents:</H3>
<P>No form fields.
<DL>
</DL>
None
None
Please fill in the name and addr fields.
据我所知,从python.org文档和我发现的每个例子我都正确地做了一切,但表单数据总是空白的。最终我需要下载POST发送的文件,但是我要暂时停止,直到我可以阅读该表格。有没有人遇到过这个?非常感谢任何帮助。
答案 0 :(得分:0)
我可能是错的,但是我认为如果您正在运行这样的基本服务器,那么您可以通过以下方式访问POST数据:
content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
post_data = self.rfile.read(content_length) # <--- Gets the data itself
如果您想使用
访问POST数据form = cgi.FieldStorage()
您将访问该 外部 基础服务器类。因此,在主要方法或类似方法中。