[Tutor] cgi FieldStorage __str__ problem - I think...

Simon Brunning SBrunning@trisystems.co.uk
Wed, 20 Jun 2001 13:59:22 +0100


> From:	Remco Gerlich [SMTP:scarblac@pino.selwerd.nl]
> > I set up a template for the email as follows:
> > 
> > mailtemplate = '''From: %(email)s
> > Subject: %(subject)s
> > Email from %(name)s
> > %(comments)s'''
> > 
> > Then I substitute the data from the form into the template as follows:
> > 
> > form = cgi.FieldStorage()
> > mailtext = mailtemplate % form
> > 
> > Trouble is, the mailtext field ends up looking like this:
> > 
> > From: MiniFieldStorage('email', 'a@b.c')
> > Subject: MiniFieldStorage('subject', 'Spam')
> > Email from MiniFieldStorage('name', 'Fred')
> > MiniFieldStorage('comments', 'Egg and chips...')
> > 
> > Looks to me like the FieldStorage object's values are instances of some
> > MiniFieldStorage class, and the __str__ method of that class is just
> > returning the __repr__. Is this correct?
> 
> Yes. The actual value is in form["email"].value, and so on.
> 
> > If so, what do I do about it?
> 
> Maybe the easiest way is to make a tiny wrapper class that calls .value:
> 
> class FieldStorageWrapper:
>    def __init__(self, fieldstorage):
>       self.fieldstorage = fieldstorage
>    def __getitem__(self, name):
>       return self.fieldstorage[name].value
> 
> mailtext = mailtemplate % FieldStorageWrapper(form)
 
I ended up with the brutally simple:

form = cgi.FieldStorage()
formstrings = {}
for formfield in form.keys():
    formstrings[formfield] = form[formfield].value
mailtext = mailtemplate % formstrings

(I tried form.values() first, but the FieldStorage object doesn't seem to
support it.)

Not pretty, but it works. Much like myself, really.
 
> Or maybe trying to do this with a single % call is a bit too cute.
 
Yeah, but it would have been cool, no?

Thanks, Remco and Roman.

Cheers,
Simon Brunning
TriSystems Ltd.
sbrunning@trisystems.co.uk




-----------------------------------------------------------------------
The information in this email is confidential and may be legally privileged.
It is intended solely for the addressee. Access to this email by anyone else
is unauthorised. If you are not the intended recipient, any disclosure,
copying, distribution, or any action taken or omitted to be taken in
reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot
accept liability for statements made which are clearly the senders own.