Python中的KeyError

问题描述 投票:1回答:2

这是我的代码:

    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 file“/ usr / lib / python2.7 / cgi.py“,第541行,> getitem引发KeyError,键KeyError:'ViewerType'

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

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

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

import cgi
form = cgi.FieldStorage()
python html cgi traceback keyerror
2个回答
1
投票

首次调用脚本渲染页面时,form dict为空。 dict只有在用户实际提交表单时才会被填充。所以将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>"

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.
© www.soinside.com 2019 - 2024. All rights reserved.