【发布时间】:2014-09-16 09:26:46
【问题描述】:
我正在尝试在 python 上使用表单,但我有 2 个问题我无法决定很长时间。
首先,如果我将文本字段留空,它会给我一个错误。网址如下:
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>'
【问题讨论】:
-
if "userName" in form:?