2014-10-02 55 views
1

G'day!Python中的KeyError

所以这是我的代码:

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 

而且,当我把它投放到浏览器,这是错误:

Traceback (most recent call last): File "/home/nandres/dbsys/mywork/James/mywork/ViewerForm.py", >line 42, in ViewerType=form['ViewerType'].value File "/usr/lib/python2.7/cgi.py", line 541, in >getitem raise KeyError, key KeyError: 'ViewerType'

和线路42是我的代码的最后一行。

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

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

import cgi 
form = cgi.FieldStorage() 

谢谢!

回答

1

当第一次叫你的脚本来渲染页面,则form字典是空的。当用户实际提交表单时,字典才会填充。因此,改变你的HTML

<option value="C" selected>Crowd Funding 

不会帮助。

因此,在尝试访问它之前,您需要测试字典。例如,

#! /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>" 
+0

感谢队友,我用你的代码来获得灵感,并让它工作。 – 2014-10-02 10:39:51

+0

非常好!谢谢你的观点。 PS。我希望你的实际程序不提供缺少结束标记的HTML等:) – 2014-10-02 10:44:36

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.