【问题标题】:Working in Python cgi with form. Empty input error在 Python cgi 中使用表单工作。空输入错误
【发布时间】: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:?

标签: python html forms cgi


【解决方案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"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多