form= cgi.FieldStorage()
print form
Prints: FieldStorage(None, None, 'age=10&name=joe').
How do I get the data from that form?
I can't use form[FieldKey], because there is no field key.
form['age'] returns a blank string
I'm using Python 2.7.
Other answers have explained why there was a problem with the request and how to fix it, but I think it might be helpful to better understand the FieldStorage object so you can recover from a bad request.
I was mostly able to duplicate your state using this:
from cgi import FieldStorage
from StringIO import StringIO
f = FieldStorage(
fp=StringIO("age=10&name=joe"),
headers={"content-length": 15, "content-type": "plain/text"},
environ={"REQUEST_METHOD": "POST"}
)
print(f) # FieldStorage(None, None, 'age=10&name=joe')
This will fail as expected:
f["age"] # TypeError: not indexable
f.keys() # TypeError: not indexable
So FieldStorage didn't parse the query string because it didn't know it should, but you can make FieldStorage manually parse it:
f.fp.seek(0) # we reset fp because FieldStorage exhausted it
# if f.fp.seek(0) fails we can also do this:
# f.fp = f.file
f.read_urlencoded()
f["age"] # 10
f.keys() # ["age", "name"]
If you ever need to get the original body from FieldStorage, you can get it from the FieldStorage.file property, the file property gets set when FieldStorage parses what it thinks is a plain body:
f.file.read() # "age=10&name=joe"
Hope this helps other fellow searchers who stumble on this question in the future.
You can try
import cgi
form = cgi.FieldStorage()
print form.getvalue("age")
as described in the more general thread How are POST and GET variables handled in Python?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With