您的位置:首页 > 其它

WSGI: 解析POST请求

2016-11-16 09:30 99 查看
当请求方式是POST时, 请求字符串将会被放在HTTP请求信息载体中发送,而不是放在URL中(这里与GET不同).  请求信息载体在WSGI服务器上, 这个服务器还提供了wsgi.input文件存储环境变量.

反馈信息的大小是一个整型数据, 可以从wsgi.input文件中读取到. PEP3333(https://www.python.org/dev/peps/pep-3333/) 里提到 包含反馈信息大小的变量 CONTENT_LENGTH 可能是空值或者出现值丢失的情况, 所以请在 try/except 代码块中进行读取.

以下脚本中的HTML 表单标记符指示浏览器做 POST请求(method="post"):

#!/usr/bin/env python

from wsgiref.simple_server import make_server
from cgi import parse_qs, escape

html = """
<html>
<body>
<form method="post" action="">
<p>
Age: <input type="text" name="age" value="%(age)s">
</p>
<p>
Hobbies:
<input
name="hobbies" type="checkbox" value="software"
%(checked-software)s
> Software
<input
name="hobbies" type="checkbox" value="tunning"
%(checked-tunning)s
> Auto Tunning
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>
<p>
Age: %(age)s<br>
Hobbies: %(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时, 变量将会被放在存在域wsgi.input文件中的HTTP请求信息中, 由WSGI 服务器一起发送.
request_body = environ['wsgi.input'].read(request_body_size)
d = parse_qs(request_body)

age = d.get('age', [''])[0] # 返回第一个年龄值
hobbies = d.get('hobbies', []) # 返回 hobbies 数组

# 防止脚本注入
age = escape(age)
hobbies = [escape(hobby) for hobby in hobbies]

response_body = html % { # 嵌入 html模板
'checked-software': ('', 'checked')['software' in hobbies],
'checked-tunning': ('', 'checked')['tunning' in hobbies],
'age': age or 'Empty',
'hobbies': ', '.join(hobbies or ['No Hobbies?'])
}

status = '200 OK'

response_headers = [
('Content-Type', 'text/html'),
('Content-Length', str(len(response_body)))
]

start_response(status, response_headers)
return [response_body]

httpd = make_server('localhost', 8051, application)
httpd.serve_forever()

将上面的代码保存到 py 脚本中并运行脚本, 然后访问一下 http://localhost:8051/ 试试.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  WSGI server POST