Reputation: 2982
I have a form with an input tag and a submit button:
<input type="file" name="filename" size="25">
I have a python file that handles the post:
def post(self):
The file that I'm receiving in the form is an .xml file, in the python post function I want to send that 'foo.xml' to another function that is going to validate it (using minixsv)
My question is how do I retrieve the file? I tried:
form = cgi.FieldStorage()
inputfile = form.getvalue('filename')
but this puts the content in the inputfile, I don't have a 'foo.xml' file per se that I can pass to the minisxv function which request a .xml file not the text...
Update I found a function that accepts text instead of an input file, thanks anyway
Upvotes: 2
Views: 2508
Reputation: 287865
Oftentimes, there's also a function to extract XML from a string. For example, minidom has parseString
, and lxml etree.XML
.
If you have the content, you can make a file-like object with StringIO:
from StringIO import StringIO
content = form.getvalue('filename')
fileh = StringIO(content)
# You can now call fileh.read, or iterate over it
If you must have a file on the disk, use tempfile.mkstemp:
import tempfile
content = form.getvalue('filename')
tmpf, tmpfn = tempfile.mkstemp()
tmpf.write(content)
tmpf.close()
# Now, give tmpfn to the function expecting a filename
os.unlink(tmpfn) # Finally, delete the file
Upvotes: 2
Reputation: 5919
This probably won't be the best answer, but why not consider using StringIO on your inputfile
variable, and passing the StringIO object as the file handle to your minisxv function? Alternately, why not open an actual new file handle for foo.xml
, save the contents of inputfile to it (i.e., via open
), and then pass foo.xml
to your minisxv function?
Upvotes: 0