Python将列表传入表单并作为列表检索
在Python的CGI中,最好的方法是什么来通过表单传递列表?
ListStr = ['State1', 'State2', 'State3']
TrVListStr = '##'.join(ListStr)
print """
<form method="post">
<input type=hidden name="state_carry" value="""+TrVListStr+"""><br />
<input type="submit" value="Submit" />
</form>
"""
提交后,我希望列表能和提交前一样。
我可以通过再次使用split(根据##规则)来获取form['state_carry'].value,但我觉得这不是个好办法。
有没有什么方法可以通过表单传递Python列表,并在之后再取出来?
谢谢。
2 个回答
1
在Python中,我会这样做。
###In the form page.
import cgi
#Convert list of values to string before passing them to action page.
ListStr=','.join(['State1', 'State2', 'State3'])
print "<input type=hidden name=\"state_carry\" value=\""+ListStr+"\"><br />"
###In the action page
import cgi
#Return the string passed in the user interaction page and transform it back to a list.
ListStr=cgi.FieldStorage().getvalue('state_carry').split(',')
3
你可以使用Python的cgi模块。文档中专门讲解了当某个字段名有多个值的情况。
基本的想法是,你可以在HTML表单中有多个同名的字段,每个字段的值可以是一个列表中的值。然后你可以使用getlist()
方法来把所有的值作为一个列表取出来。例如:
print "<form method=\"post\">"
for s in ListStr:
print "<input type=hidden name=\"state_carry\" value=\"" + s + "\"><br />"
print "<input type=\"submit\" value=\"Submit\" />"
print "</form>"
然后在你的CGI脚本中,你会有类似这样的代码:
MyList = form.getlist("state_carry")