R
Ron Garret
I'm trying to figure out how to use BaseHTTPServer. Here's my little
test app:
=================================
#!/usr/bin/python
from BaseHTTPServer import *
import cgi
class myHandler(BaseHTTPRequestHandler):
def do_GET(r):
s = ''
try:
s = cgi.parse_qs(r.rfile.read(int(r.headers.get
("Content-length"))), 1)
except:
pass
r.send_response(200)
r.send_header("Content-type", "text/html")
r.end_headers()
r.wfile.write("""
<form method=post action=foo>
<input type=text name=text1 value="">
<input type=text name=text2 value="">
<input type=submit>
</form> %s
""" % s)
def do_POST(r):
r.do_GET()
d = HTTPServer(('', 1024), myHandler)
d.serve_forever()
===================================
Two questions:
1. The line:
s = cgi.parse_qs(r.rfile.read(int(r.headers.get("Content-length"))), 1)
feels like a horrible hack. It seems like this would be a better
alternative:
s = cgi.parse(r.rfile)
but that doesn't actually work. Why? What is the Right Way to parse
form data in a BaseHTTPServer?
2. Despite the fact that I'm passing a 1 for the keep_blank_values
argument to cgi.parse_qs, it doesn't actually keep blank values. Is
this a bug, or am I doing something wrong?
Thanks,
rg
test app:
=================================
#!/usr/bin/python
from BaseHTTPServer import *
import cgi
class myHandler(BaseHTTPRequestHandler):
def do_GET(r):
s = ''
try:
s = cgi.parse_qs(r.rfile.read(int(r.headers.get
("Content-length"))), 1)
except:
pass
r.send_response(200)
r.send_header("Content-type", "text/html")
r.end_headers()
r.wfile.write("""
<form method=post action=foo>
<input type=text name=text1 value="">
<input type=text name=text2 value="">
<input type=submit>
</form> %s
""" % s)
def do_POST(r):
r.do_GET()
d = HTTPServer(('', 1024), myHandler)
d.serve_forever()
===================================
Two questions:
1. The line:
s = cgi.parse_qs(r.rfile.read(int(r.headers.get("Content-length"))), 1)
feels like a horrible hack. It seems like this would be a better
alternative:
s = cgi.parse(r.rfile)
but that doesn't actually work. Why? What is the Right Way to parse
form data in a BaseHTTPServer?
2. Despite the fact that I'm passing a 1 for the keep_blank_values
argument to cgi.parse_qs, it doesn't actually keep blank values. Is
this a bug, or am I doing something wrong?
Thanks,
rg