2014-10-02 258 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.