python从html表单接收文件

时间:2011-10-17 22:19:53

标签: python python-3.x

我有一个带有输入标记和提交按钮的表单:

<input type="file" name="filename" size="25">

我有一个处理帖子的python文件:

def post(self):

我在表单中收到的文件是.xml文件,在python post函数中我想将'foo.xml'发送到另一个要验证它的函数(使用minixsv)

我的问题是如何检索文件?我试过了:

form = cgi.FieldStorage()

inputfile = form.getvalue('filename')

但这会把内容放在inputfile中,我本身没有'foo.xml'文件,我可以传递给minisxv函数,该函数请求.xml文件而不是文本......

更新我找到了一个接受文字而不是输入文件的功能,谢谢

2 个答案:

答案 0 :(得分:2)

通常,还有一个从字符串中提取XML的函数。例如,minidom有parseString和lxml etree.XML

如果您有内容,则可以使用StringIO制作类似文件的对象:

from StringIO import StringIO
content = form.getvalue('filename')
fileh = StringIO(content)
# You can now call fileh.read, or iterate over it

如果您的磁盘上必须有文件,请使用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

答案 1 :(得分:0)

这可能不是最佳答案,但为什么不考虑在inputfile变量上使用StringIO,并将StringIO对象作为文件句柄传递给minisxv函数?或者,为什么不为foo.xml打开一个实际的新文件句柄,将inputfile的内容保存到它(即通过open),然后将foo.xml传递给你的minisxv函数?