Reputation: 692
I have an apache + mod_wsgi + python3.1 setup. (Plain, no Django or other framework.) I can write apps that output HTML, but I can't seem to get a basic web form + POST parser to work so I can also handle input. I've found some examples online that are several years old and use python2, and several pages describing the "issues you should be aware of" with python3 that make the python2 examples obsolete (long list of encoding issues new to python3, etc.)
Would anyone happen to have python3 code ("def application(environ, start_response):...") that puts up a small UTF-8 web form with a couple of short menus that, when you submit (POST) it, puts those UTF-8 menu choices into python3 strings? A python3 script that handles the issues properly regarding telling it the right number of bytes to read from the request, doesn't munge the UTF-8 for non-ASCII chars, doesn't use deprecated functions, etc., that can be used as a bare-bones template by people trying to use mod_wsgi + python3 for input as well as output?
Upvotes: 3
Views: 2692
Reputation: 34116
from urllib.parse import parse_qsl
def application(environ, start_response):
try:
path = environ['PATH_INFO']
except KeyError:
path = environ['REQUEST_URI'].decode('utf-8').split('=', 1)[1]
method = environ['REQUEST_METHOD']
get = dict(parse_qsl(environ['QUERY_STRING'], keep_blank_values=True))
post = dict(parse_qsl(environ['wsgi.input'].read().decode('utf-8')))
if path == '/my_form':
start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])
yield '''\
<form action="" method="POST">
<label for="name">What is your name?</label>
<input type="text" name="name"/>
<input type="submit"/>
</form>'''.encode('utf-8')
if method == 'POST' and 'name' in post:
yield "<p>Hello, {}!</p>".format(post['name']).encode('utf-8')
else:
start_response('404 Not Found', [('Content-Type', 'text/html')])
yield "<h1>404 Not Found</h1>".encode('utf-8')
Upvotes: 4
Reputation: 34116
You probably don't want any frameworks, but I encourage you to try Bottle. It doesn't require any installation, you can just put the bottle.py file into your project folder and you're ready to go.
And yes, it works with Python 3!
import bottle
from bottle import get, post, request
@get('/my_form')
def show_form():
return '''\
<form action="" method="POST">
<label for="name">What is your name?</label>
<input type="text" name="name"/>
<input type="submit"/>
</form>'''
@post('/my_form')
def show_name():
return "Hello, {}!".format(request.POST.name)
application=bottle.default_app() # run in a WSGI server
#bottle.run(host='localhost', port=8080) # run in a local test server
Upvotes: 2