在Python cgi中使用表单.空输入错误 [英] Working in Python cgi with form. Empty input error
问题描述
我正在尝试在python上使用表单,但有2个问题我无法确定很多时间.
I am trying to work with forms on python and I have 2 problems which I can't decide for a lot of time.
首先,如果我将文本字段留空,则会给我一个错误.这样的网址:
First if I leave the text field empty, it will give me an error. url like this:
http://localhost/cgi-bin/sayHi.py?userName=
我尝试了很多类似try的变体,但是,如果用户名是global或local而ect但没有结果,则等同于php if(isset(var)).如果用户将输入留空但按下按钮Submit,我只想向用户提供诸如填写表格"之类的消息.
I tried a lot of variants like try except, if username in global or local and ect but no result, equivalent in php if (isset(var)). I just want to give a message like 'Fill a form' to user if he left the input empty but pressed button Submit.
第二,我想在提交后保留打印在输入字段上的内容(例如搜索表单).在php中很容易做到,但是我无法在python中做到这一点
Second I want to leave what was printed on input field after submit(like search form). In php it's quite easy to do it but I can't get how to do it 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>'
推荐答案
在 cgi
文档页面是这些单词:
On the cgi
documentation page are these words:
FieldStorage实例可以像Python字典一样被索引.它允许使用
in
运算符
获得所需内容的一种方法是使用 in
运算符,如下所示:
One way to get what you want is to use the in
operator, like so:
form = cgi.FieldStorage()
if "userName" in form:
print "<h1>Hi there, %s!</h1>" % cgi.escape(form["userName"].value)
在同一页面上:
实例的
value
属性产生字段的字符串值.getvalue()
方法直接返回此字符串值.它也接受可选的第二个参数作为默认值,如果请求的键不存在,则返回默认值.
The
value
attribute of the instance yields the string value of the field. Thegetvalue()
method returns this string value directly; it also accepts an optional second argument as a default to return if the requested key is not present.
为您提供的第二种解决方案可能是:
A second solution for you might be:
print "<h1>Hi there, %s!</h1>" % cgi.escape(form.getvalue("userName","Nobody"))
这篇关于在Python cgi中使用表单.空输入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!