2014-07-24 55 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"))