cgi.py

Michael McLay (mclay@eeel.nist.gov)
Tue, 21 Jun 94 11:29:18 EDT

"N.G.Smith" writes:
> I have been using the cgi.py stuff that you posted recently in response
> to a request I made on the python list. I have found a bug in the
> unquoting code. It seems to me that it assumes that hex digits will be
> uppercase. In fact the urllib module escapes using lowercase hex
> digits. My fix was to replace all the conversion code with a call to
> urllib.unquote.

Thanks for the bug report. The fix also eliminated some ugly code. I've
incorporated your suggestion and attached the update.

Michael

----------------------------cgi.py--------------------------------
# A class for wrapping the WWW Forms Common Gateway Interface (CGI)
# Michael McLay, NIST mclay@eeel.nist.gov 6/14/94

import string
import regsub
import sys
import os
import urllib

# class FormContent parses the name/value pairs that are passed to a
# server's CGI by GET, POST, or PUT methods by a WWW FORM. several
# specialized FormContent dictionary access methods have been added
# for convenience.

# function return value
#
# keys() all keys in dictionary
# has_key('key') test keys existance
# values('key') key's list
# indexed_value('key' index) nth element from key's value list
# value(key) key's unstripped value
# length(key) number of elements in key's list
# stripped(key) key's value with whitespace stripped
# pars() full dictionary

# The FormContent constructor creates a dictionary from the name/value pairs
# passed through the CGI interface.

class FormContent:
def __init__(self):
if os.environ['REQUEST_METHOD'] == 'POST':
self.qs = sys.stdin.read(string.atoi(
os.environ['CONTENT_LENGTH']))
else:
self.qs = os.environ['QUERY_STRING']
name_value_pairs = string.splitfields(self.qs, '&')
self.t = {}
for name_value in name_value_pairs:

nv = string.splitfields(name_value, '=')
name = nv[0]
value = urllib.unquote(nv[1])
if len(value):
if self.t.has_key (name):
self.t[name].append(value)
else:
self.t[name] = [value]
def keys(self):
return self.t.keys()
def has_key(self, key):
return self.t.has_key(key)
def values(self,key):
if self.t.has_key(key):return self.t[key]
else: return None
def indexed_value(self,key, location):
if self.t.has_key(key):
if len (self.t[key]) > location:
return self.t[key][location]
else: return None
else: return None
def value(self,key):
if self.t.has_key(key):return self.t[key][0]
else: return None
def length(self,key):
return len (self.t[key])
def stripped(self,key):
if self.t.has_key(key):return string.strip(self.t[key][0])
else: return None
def pars(self):
return self.t

def print_header(str):
print 'Content-type: text/html\n\n'
print '<HEADER>\n<TITLE>' + str + '</TITLE>\n</HEADER>\n'

def print_title(str):
print "<H1>" +str+"</H1>\n"

def test():
gs = FormContent()
print gs.values('uid')

#test()