A utility routine to check whether a form element is a valid number, and set it to a default value if it is missing.
# - - - y e a r C h e c k def yearCheck(form, eltName, desc, default): '''Validate or assign a default value to a form element. [ (form is a cgi.FieldStorage instance) and (eltName is the name of a form element) and (desc is a textual description of that element) and (default is its default value) -> if eltName is not in form -> return default else if eltName is in the form and a valid int -> return that int in year-number format else -> raise ScriptError ] '''
Years are always formatted in
format; see Section 14.4, “
#-- 1 # [ if eltName is in form -> # rawYear := the corresponding value # else -> # return default ] try: rawYear = form[eltName].value except KeyError: return default #-- 2 # [ if rawYear is a valid int -> # return that int in year-number format # else -> raise ScriptError ] try: yearNo = int(rawYear) return '%03d' % yearNo except lib.ScriptError: raise ScriptError("Not a valid %s: %s" % (desc, rawYear))