我正在Linux上使用tomcat 9.0,python 3.6。 我的测试脚本适用于Get请求,但不适用于Post请求。 每当我发送发布请求时,该请求都将挂起,看起来它正在等待sys.stdin。如果我使用form = cgi.FieldStorage(),它也会挂起。如果我打印出content_length,则为None。
import sys
# Import modules for CGI handling
import cgi, cgitb
import os
import traceback
sys.stderr = sys.stdout
print("Content-type:text/html\r\n\r\n")
print("<html>")
print("<head>")
print("<title>Hello - Second CGI Program</title>")
print("</head>")
print("<body>")
print("########################################")
cgitb.enable()
if os.environ['REQUEST_METHOD'] == 'GET':
# Create instance of FieldStorage
#cgi.print_environ_usage()
form = cgi.FieldStorage()
# Get data from fields
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')
elif os.environ['REQUEST_METHOD'] == 'POST':
# Create instance of FieldStorage
# cgi.print_environ_usage()
#print(os.environ['CONTENT_LENGTH'])
#this does not work, the request never response, looks like waiting for something
form = cgi.FieldStorage()
# Get data from fields
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')
elif os.environ['REQUEST_METHOD'] == 'POST2':
# this does not work either, taking suggestion from other post.
POST={}
post_length = int(os.environ['CONTENT_LENGTH'])
# post_length stores byte count, but stdin.read, apparently, takes the character count
post_string = sys.stdin.buffer.read(post_length).decode('utf-8')
args=post_string.split('&')
for arg in args:
t=arg.split('=')
if len(t)>1: k, v=arg.split('='); POST[k]=v
# Get data from fields
first_name = POST.get('first_name')
last_name = POST.get('last_name')
else:
first_name = 'None'
last_name = 'None'
#print("<h2>Hello %s %s</h2>" % (first_name, last_name))
print("</body>")
print("</html>")
测试时,我使用curl命令,例如
curl -X "POST" "http://localhost:8080/test.py?first_name=john&last_name=black"
curl -X "GET" "http://localhost:8080/test.py?first_name=john&last_name=black"