Daniel J. Popowich
dpopowich at mtrsd.k12.ma.us
Wed Oct 15 12:31:41 EST 2003
I found myself wanting methods of util.FieldStorage that are found in the cgi module since python 2.2, getfirst and getlist. They save tons of code of the form: if form.has_key('foo'): foo = form['foo'] if type(foo) is not type([]): foo = [foo] else: foo = [] which can cause code-clutter if you have a number of form variables. Instead, one can simply write: foo = form.getlist('foo') See the cgi documentation for 2.2 or later for details about these methods and how they can help you reduce code and write safer code to protect against malformed requests. I extended util.FieldStorage to add those two methods plus a get() (which behaves like a standard dict.get) and thought others might like the code (which I didn't write in whole, but stole mostly from modules cgi and UserDict). If found useful by many, perhaps they can be included in the 3.1 distribution? Enjoy, Daniel Popowich Network Specialist MTRSD ====================================================================== from mod_python import util class form(util.FieldStorage): def get(self, key, default=None): if not self.has_key(key): return default return self[key] def getfirst(self, key, default=None): if self.has_key(key): value = self[key] if type(value) is type([]): return value[0] else: return value else: return default def getlist(self, key): if self.has_key(key): value = self[key] if type(value) is type([]): return value else: return [value] else: return []
|