alf*_*eza 3 python wsgi wsgiref
我正在尝试从简单的表单中捕获 POST 数据。
这是我第一次使用 WSGIREF,我似乎找不到正确的方法来做到这一点。
This is the form:
<form action="test" method="POST">
<input type="text" name="name">
<input type="submit"></form>
Run Code Online (Sandbox Code Playgroud)
并且该函数显然缺少正确的信息来捕获帖子:
def app(environ, start_response):
"""starts the response for the webserver"""
path = environ[ 'PATH_INFO']
method = environ['REQUEST_METHOD']
if method == 'POST':
if path.startswith('/test'):
start_response('200 OK',[('Content-type', 'text/html')])
return "POST info would go here %s" % post_info
else:
start_response('200 OK', [('Content-type', 'text/html')])
return form()
Run Code Online (Sandbox Code Playgroud)
您应该读取来自服务器的响应。
从nosklo对类似问题的回答:“ PEP 333说你必须阅读 environ['wsgi.input']。”
测试代码(改编自此答案):
警告:此代码仅用于演示目的。
警告:尽量避免硬编码路径或文件名。
def app(environ, start_response):
path = environ['PATH_INFO']
method = environ['REQUEST_METHOD']
if method == 'POST':
if path.startswith('/test'):
try:
request_body_size = int(environ['CONTENT_LENGTH'])
request_body = environ['wsgi.input'].read(request_body_size)
except (TypeError, ValueError):
request_body = "0"
try:
response_body = str(request_body)
except:
response_body = "error"
status = '200 OK'
headers = [('Content-type', 'text/plain')]
start_response(status, headers)
return [response_body]
else:
response_body = open('test.html').read()
status = '200 OK'
headers = [('Content-type', 'text/html'),
('Content-Length', str(len(response_body)))]
start_response(status, headers)
return [response_body]
Run Code Online (Sandbox Code Playgroud)