使用Python CGI处理表单时的空输入错误
我在用Python处理表单时遇到了两个问题,纠结了很久都没解决。
第一个问题是,如果我把文本框留空,提交后就会报错,网址会变成这样:
http://localhost/cgi-bin/sayHi.py?userName=
我尝试了很多方法,比如用try except,检查用户名是否在全局或局部变量中等等,但都没有效果。在PHP中可以用if (isset(var))来判断。我只想在用户按下提交按钮但没有填写内容时,给他们一个提示,比如“请填写表单”。
第二个问题是,我希望在用户提交后,输入框里能保留他们之前输入的内容(就像搜索表单那样)。在PHP中这很简单,但我不知道在Python中该怎么做。
这是我用来测试的文件:
#!/usr/bin/python
import cgi
print "Content-type: text/html \n\n"
print """
<!DOCTYPE html >
<body>
<form action = "sayHi.py" method = "get">
<p>Your name?</p>
<input type = "text" name = "userName" /> <br>
Red<input type="checkbox" name="color" value="red">
Green<input type="checkbox" name="color" value="green">
<input type = "submit" />
</form>
</body>
</html>
"""
form = cgi.FieldStorage()
userName = form["userName"].value
userName = form.getfirst('userName', 'empty')
userName = cgi.escape(userName)
colors = form.getlist('color')
print "<h1>Hi there, %s!</h1>" % userName
print 'The colors list:'
for color in colors:
print '<p>', cgi.escape(color), '</p>'
1 个回答
2
在cgi
的文档页面上,有这么一句话:
FieldStorage实例可以像Python字典一样进行索引。它允许使用
in
运算符进行成员测试。
获取你想要的内容的一种方法是使用in
运算符,像这样:
form = cgi.FieldStorage()
if "userName" in form:
print "<h1>Hi there, %s!</h1>" % cgi.escape(form["userName"].value)
同一页面上还有一句:
这个实例的
value
属性会返回字段的字符串值。getvalue()
方法直接返回这个字符串值;它还可以接受一个可选的第二个参数,作为默认值,如果请求的键不存在时返回。
你可以尝试的第二种解决方案是:
print "<h1>Hi there, %s!</h1>" % cgi.escape(form.getvalue("userName","Nobody"))