当请求方法是POST的时候,查询字符串将从HTTP请求体中传递而不是通过URL。请求体是WSGI服务器提供的类似于环境变量的wsgi.input文件。
有必要知道应答体的大小,以便从wsgi.input中读出它。WSGI明细规定,CONTENT_LENGTH变量来存储大小,它可以为空或者被忽略,所以读它的时候把它放到一个try/except块中。
这个脚本应该被存储为parsing_post.wsgi
#coding=utf-8
#!/usr/bin/env python
from wsgiref.simple_server import make_server
from cgi import parse_qs, escape
html = """
<html>
<body>
<form method="POST" action="parsing_post.wsgi">
<p>
Age: <input type="text" name="age">
</p>
<p>
Hobbies:
<input name="hobbies" type="checkbox" value="software"> Software
<input name="hobbies" type="checkbox" value="tunning"> Auto Tunning
</p>
<p>
<input type="submit" value="Submit">
</p>
<p>
Aage: %s<br>
Hobbies: %s
</p>
</body>
</html>
"""
def application(environ, start_response):
# 环境变量CONTENT_LENGTH可以为空或忽略
try:
request_body_size = int(environ.get('CONTENT_LENGTH', 0))
except (ValueError):
request_body_size = 0
# 当请求方法是POST的时候,查询字符串将从HTTP请求体中传递,这个请求体是由WSGI服务器传过来的类似于文件的wsgi.input环境变量中。
request_body = environ['wsgi.input'].read(request_body_size)
d = parse_qs(request_body)
print d
age = d.get('age', [''])[0] # 返回第一个age的值
hobbies = d.get('hobbies', []) # 返回hobbies的列表
# 不要忘记转义用户输入,防止脚本注入
age = escape(age)
hobbies = [escape(hobby) for hobby in hobbies]
response_body = html % (age or 'Empty', ','.join(hobbies or ['No Hobbies']))
status = '200 OK'
response_header = [('Content-Type', 'text/html'), ('Content-Length', str(len(response_body)))]
start_response(status, response_header)
return [response_body]
httpd = make_server('localhost', 8051, application)
httpd.serve_forever()