Database Reference
In-Depth Information
The
FieldStorage
object contains information for parameters submitted via either
get
or
post
requests, so you need not know which method was used to send the request.
The object also contains an element for each parameter present in the environment. Its
key()
method returns a list of available parameter names:
param_names
=
params
.
keys
()
If a given parameter,
name
, is single-valued, the value associated with it is a scalar that
you can access as follows:
val
=
params
[
name
]
.
value
If the parameter is multiple-valued,
params[name]
is a list of
MiniFieldStorage
objects
that have
name
and
value
attributes. Each has the same name (it will be equal to
name
)
and one of the parameter's values. To create a list containing all the values for such a
parameter, do this:
val
=
[]
for
item
in
params
[
name
]:
val
.
append
(
item
.
value
)
To avoid having to distinguish whether a parameter has a single value or multiple values,
use
getlist()
. The following listing shows how to get the parameter names and loop
through each parameter to print its name and value, printing multiple-valued param‐
eters as a comma-separated list:
params
=
cgi
.
FieldStorage
()
param_names
=
params
.
keys
()
param_names
.
sort
()
print
(
"<p>Parameter names:
%s
</p>"
%
param_names
)
items
=
[]
for
name
in
param_names
:
val
=
','
.
join
(
params
.
getlist
(
name
))
items
.
append
(
"name="
+
name
+
", value="
+
val
)
print
(
make_unordered_list
(
items
))
Python raises an exception if you try to access a parameter not present in the
Field
Storage
object. To avoid this, use
has_key()
to find out whether the parameter exists:
if
params
.
has_key
(
name
):
print
(
"parameter
%s
exists"
%
name
)
else
:
print
(
"parameter
%s
does not exist"
%
name
)
Single-valued parameters have attributes other than
value
. For example, a parameter
representing an uploaded file has additional attributes you can use to get the file's con‐
tents.
Recipe 20.8
discusses this further.
The
cgi
module expects URL parameters to be separated by
&
characters. To construct
a hyperlink that points to a Python script based on the
cgi
module, don't separate the
parameters by
;
characters.