Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from FieldStorage?

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.

like image 710
Davide Andrea Avatar asked Mar 07 '26 04:03

Davide Andrea


2 Answers

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.

like image 66
Jaymon Avatar answered Mar 08 '26 18:03

Jaymon


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?

like image 24
ggorlen Avatar answered Mar 08 '26 18:03

ggorlen