1

这是我的代码:

    print """\
<form method="post">
    Please enter Viewer Type:<br />
<table>
"""

#Viewer Type
print "<tr><td>Viewer Type<select name=""ViewerType"">"
print """\
    <option value="C">Crowd Funding
    <option value="P">Premium
"""
#do it button

print """\
    <input type="submit" value="OK" />
"""

print """\
</form>
</body>
<html>
"""

ViewerType=form['ViewerType'].value

而且,当我将它提供给浏览器时,这是错误:

回溯(最后一次调用):文件“/home/nandres/dbsys/mywork/James/mywork/ViewerForm.py”,>第 42 行,在 ViewerType=form['ViewerType'].value 文件“/usr/lib/ python2.7/cgi.py",第 541 行,在 > getitem raise KeyError , key KeyError: 'ViewerType'

第 42 行是我的代码的最后一行。

该错误实际上并没有影响功能,并且一切正常,但我真的不希望它弹出。任何建议/见解将不胜感激。

顺便说一句,我的代码顶部有这个:

import cgi
form = cgi.FieldStorage()
4

2 回答 2

1

当您的脚本第一次被调用来呈现页面时,formdict 是空的。只有当用户实际提交表单时,字典才会被填写。因此,将您的 HTML 更改为

<option value="C" selected>Crowd Funding

不会有帮助的。

因此,您需要在尝试访问 dict 之前对其进行测试。例如,

#! /usr/bin/env python

import cgi

form = cgi.FieldStorage()

print 'Content-type: text/html\n\n'

print "<html><body>"
print """\
<form method="post">
    Please enter Viewer Type:<br />
<table>
"""

#Viewer Type
print "<tr><td>Viewer Type<select name=""ViewerType"">"

print """\
    <option value="C">Crowd Funding
    <option value="P">Premium
"""
#do it button

print """\
    <input type="submit" value="OK" />
"""

print "</table></form>"

if len(form) > 0:
    ViewerType = form['ViewerType'].value
    print '<p>Viewer Type=' + ViewerType + '</p>'
else:
    print '<p>No Viewer Type selected yet</p>'

print "</body></html>"
于 2014-10-02T08:04:33.570 回答
0

如果您不希望它弹出,则简单的解决方案:

try:
    ViewerType=form['ViewerType'].value
except KeyError:
    pass

它会起作用,但我建议您调试代码并找出出现 KeyError 的原因。从https://wiki.python.org/moin/KeyError

Python raises a KeyError whenever a dict() object is requested (using the format a = adict[key]) and the key is not in the dictionary.
于 2014-10-02T07:09:06.597 回答