Hidden CGI fields in HTML

Michael P. Reilly arcege at shore.net
Tue Aug 10 11:26:08 EDT 1999

Oleg Broytmann <phd at emerald.netskate.ru> wrote:
: On Tue, 10 Aug 1999, Ian Clarke wrote:
:> On a related issue, you are clearly experienced in using CGI with
:> Python.  I couldn't understand why cgi.FieldStorage returned a
:> dictionary which contained MiniFieldStorage objects (which must be
:> accessed using the .value field) rather than just the data itself.  This
:> would be much more convenient as I see it.  Any ideas?

:    There are, actually, some more issues on using FieldStorage, for
: example, you cannot ask for non-existing field:

: v = form["nofield"].value

:    will raise KeyError. And there is no way to emulate dict.get()...

Yes, you can
  if form.has_key("nofield"):
    if type(form["nofield"]) is type([]):
      nofield_value = map(lambda e: e.value, form["nofield"])
      nofield_value = form["nofield"].value
    nofield_value = None

But see below.

:    Oh, yes, I think I know why there is .value! What if your form has more
: than one value for some key? Like in the following GET:

: http://my.server/my/cgi/prog.py?city=Moscow&city=Paris&city=London

:    How do you get the value? How do you recognize thera are many values?
: Currently, you try to ask for form["city"], if the field exists you try to
: ask it for .value, but if the .value does not exists, you know it is a
: list:

:    for f in form["city"]:
:       print f.value

Actually, the reason is more of: what to do about file-uploads, where
you have the filename and the contents being given.  The FieldStorage
object will get a "filename" attribute, the opened file will be in
"file", and when you access "value" it will read the data from the

To correct my code snippet above to handle files you have:
  # if nofield_value is of type:
  # None:  field not in form
  # list:  multiple values
  # tuple: tuple of the filename and file object
  # string: the string data from the form
  def get_field(form, fieldname):
    if form.has_key(fieldname):
      value = get_field_data(form[fieldname])
      value = None
    return value
  def get_field_data(field):
    if type(field) is type([]):
      # recursively handle the list (could have list of list of files)
      value = map(get_field_data, field)
    elif hasattr(field, "file"):
      value = (field.filename, field.file)
      value = field.value
    return value

I suggest reading the comments in Lib/cgi.py for more information.


More information about the Python-list mailing list