2014-07-24 57 views
2

我想在python上使用窗体,我有两个问题,我不能决定很多时间。在窗体中使用Python cgi工作。空输入错误

首先,如果我将文本字段留空,它会给我一个错误。网址是这样的:

http://localhost/cgi-bin/sayHi.py?userName= 

我尝试了很多喜欢尝试不同的,变异的,如果用户名在全局或局部和ECT,但没有结果,相当于在PHP如果(isset(VAR))。我只是想给用户留言,如“填写表单”,如果他留下输入空的,但按下按钮提交。

第二我想离开提交后打印在输入栏上的内容(如搜索表单)。在PHP它很容易做,但我不能让怎么办呢蟒蛇

这里是它在我的测试文件

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

'如果以 “username”:'? – Kevin

回答

1

cgi documentation page是这些话:

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"))