[Tutor] how to pass a list or a dictionary variable in cgi script
Lance E Sloan
lsloan@umich.edu
Thu, 26 Jul 2001 08:10:14 -0400
"Abhiram Singh Kushwah" wrote:
> I'm repeating my question again:
> how to pass a list or a dictionary variable from one web page to another page
>
> Anyway I'v pass a list or dictionary element separatly
> from one web page to another page but I want to pass whole list or dictionary
> as a single variable.
That's not very difficult, really. Let's say you have a list, x, and
you want to put it on a page, in a form, so that when the user submits
the form, it will be submitted back to the CGI. Here's how you put it
in the form:
x = ['a', 'b', 'c']
print '<input type="hidden" name="x" value="%s">' % (x)
The resulting HTML will be:
<input type="hidden" name="x" value="['a', 'b', 'c']">
Of course, if your list had anything that could cause problems with
HTML (for example, >, <, or "), you would have to do something with
those before printing.
For the CGI to turn it back into a list, you would have to do this:
form = cgi.FieldStorage()
x = eval(form.getvalue('x')) # Danger! See below.
I think I'm using the cgi module correctly here. Of course, you will
probably want to do some checking before the call to eval(), like, is
there really a field "x" in this form, etc. And after the eval, check
that the variable x really points at a list object, like you expected.
A few words about security: This is very dangerous! Somebody could
cause you a lot of trouble by editing their own copy of the form and
putting something else in hidden field "x", then submit it to your
CGI. They could put in some Python code that would delete files, crash
your computer, just about anything. For example, what would the
following do if submitted to this CGI:
<input type="hidden" name="x" value="sys.exit()">
Assuming your CGI imported the sys module, your CGI would simply exit.
For that reason, I do not use this method, even though it seems very
clever. I always break lists up and store their elements in separate
form fields, all with the same name, of course. I believe
cgi.FieldStorage() will automatically assemble them back into a list.
You can translate this into use with dictionaries, too. Using the
dangerous eval() method, you could easily reassemble your dictionary
with one command. Using the safer method, you would convert your
dictionary to a list, break it up and put it in the form, then when
it's submitted, recreate the list and convert it back into a
dictionary. The safer method won't take that much more work and you
will feel a lot more comfortable.