问题
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=
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.
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
Here is my test file with it
#!/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>' 
    回答1:
On the cgi documentation page are these words:
The FieldStorage instance can be indexed like a Python dictionary. It allows membership testing with the
inoperator
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)
From the same page:
The
valueattribute 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"))
    来源:https://stackoverflow.com/questions/24940235/working-in-python-cgi-with-form-empty-input-error