I am trying to catch POST data from a simple form.
This is the first time I am playing around with WSGIREF and I can't seem to find the correct way to do this.
This is the form:
<form action="test" method="POST">
<input type="text" name="name">
<input type="submit"></form>
And the function that is obviously missing the right information to catch post:
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()
You should be reading responses from the server.
From nosklo's answer to a similar problem: "PEP 333 says you must read environ['wsgi.input']."
Tested code (adapted from this answer):
Caveat: This code is for demonstrative purposes only.
Warning: Try to avoid hard-coding paths or filenames.
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]