BaseHTTPServer weirdness

Steve Holden steve at holdenweb.com
Mon Sep 11 21:31:26 CEST 2006


Ron Garret wrote:
> 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?
> 
The normal way is

s = cgi.parse()

since the CGI script sees the client network socket (after consumption 
of HTTP headers) as its standard input. However I'm not sure how much it 
currently does in the way on handling strange inputs like gzip 
compressed data.

> 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?
> 
Sounds like a bug, but then since your parsing looks buggy I'm surprised 
you get anything at all. Try using a keyword argument 
keep_blank_values=1 just in case the order has changed or something 
daft. But fix your parsing first.

The other thing to note is that since you are putting a dictionary's 
string representation out straight into your HTML if there are odd 
characters in it this may give you strange output in the browser, so you 
should view the page source to ensure that's not the case. Which it 
probably isn't ...

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list