[mod_python] Re: Specifying GET/POST method for FieldStorage

Graham Dumpleton grahamd at dscpl.com.au
Mon Mar 13 18:19:33 EST 2006


=?iso-8859-1?Q?Fr=E9d=E9ric_Jolliton?= wrote ..
> [Since everyone is top posting, I will don't take the time to
> copy&paste parts of my previous post for the context..]
> 
> To summarize, I'm proposing:
> 
> util.FieldStorage()                   # as usual, return all fields
> util.FieldStorage( source = 'all' )   # same as above
> util.FieldStorage( source = 'query' ) # only fields from QS
> util.FieldStorage( source = 'post' )  # only fields from POST method

You do realise you could do this by creating your own class derived
from FieldStorage? Your derived class would just need to put an
appropriate wrapper (or not) around the "req" object before passing
it to the FieldStorage base class constructor.

To get you started, have a look at the following test code:

import types

from mod_python import apache, util

class _Req1:
  def __init__(self, req):
    self.__req = req
    self.__args = None
  def __getattr__(self, name):
    if name == "args":
      return self.__args
    else:
      return getattr(self.__req, name)

class _Req2:
  def __init__(self, req):
    self.__req = req
    self.__method = None
  def __getattr__(self, name):
    if name == "method":
      return self.__method
    else:
      return getattr(self.__req, name)

def dump(req, form):
  args = {}

  # Merge form data into list of possible
  # arguments. Convert the single item lists
  # back into values.
  
  for field in form.list:
    if field.filename:
      value = field
    else:
      value = field.value
      
    if args.has_key(field.name):
      args[field.name].append(value)
    else:
      args[field.name] = [value]
  
    for arg in args.keys():
      if type(args[arg]) == types.ListType:
        if len(args[arg]) == 1:
          args[arg] = args[arg][0]

    # Some strange forms can result in fields
    # where the key value is None. Wipe this out
    # just in case this happens as can cause
    # problems later.

    if args.has_key(None):
      del args[None]

  req.write(str(args))

def handler(req):
  req.content_type = 'text/plain'

  form1 = util.FieldStorage(_Req1(req))
  req.write("post=")
  dump(req, form1)

  req.write("\n")

  form2 = util.FieldStorage(_Req2(req))
  req.write("args=")
  dump(req, form2)

  return apache.OK



More information about the Mod_python mailing list