gpt4 book ai didi

python - 在带有表单的 Python cgi 中工作。空输入错误

转载 作者:行者123 更新时间:2023-11-27 23:54:22 26 4
gpt4 key购买 nike

我正在尝试在 python 上使用表单,但我有 2 个问题,我花了很长时间无法决定。

首先,如果我将文本字段留空,它会给我一个错误。像这样的网址:

http://localhost/cgi-bin/sayHi.py?userName=

我尝试了很多变体,比如 try except,if username in global or local 等等,但没有结果,等同于 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>'

最佳答案

关于cgi documentation page这些词是:

The FieldStorage instance can be indexed like a Python dictionary. It allows membership testing with the in operator

获得所需内容的一种方法是使用 in 运算符,如下所示:

form = cgi.FieldStorage()

if "userName" in form:
print "<h1>Hi there, %s!</h1>" % cgi.escape(form["userName"].value)

来自同一页面:

The value attribute of the instance yields the string value of the field. The getvalue() 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.

第二个解决方案可能是:

print "<h1>Hi there, %s!</h1>" % cgi.escape(form.getvalue("userName","Nobody"))

关于python - 在带有表单的 Python cgi 中工作。空输入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24940235/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com