【发布时间】:2010-06-20 00:15:28
【问题描述】:
我必须创建一个 HTML 表单并使用 python-cgi 获取数据。 HTML 表单要求用户提交名字和姓氏,然后 python 脚本应该获取表单中生成的数据。我已经阅读了教程并尝试使用它来使其工作,但它似乎没有发生。 HTML 代码:
<form method = "POST" action ="http://localhost/cgi-bin/pyfile_test.py">
<p>First Name: <input type="text" name="firstname">
<p>Last Name: <input type="text" name="lastname">
<p>Click here to submit the form:<input type="submit" value="Submit">
<input type="hidden" name="session" value="1898fd">
</form>
提取数据的python脚本
#!c:/Python26/python.exe -u
import cgi, cgitb
cgitb.enable()
def main()
print "Content-type: text/html\n"
print
form = cgi.FieldStorage()
if form.has_key("firstname") amd form["firstname"].value !="":
print "<h1>Hello", form["firstname"].value, "</h1>"
else:
print "<h1> Error!Wrong!</h1>
main()
当我将 html 表单指向上面的脚本时,它不起作用,但是当我将它指向下面的脚本时,它会起作用。
#!c:/Python26/python.exe -u
import cgi, cgitb
cgitb.enable()
print "Content-type: text/html"
print
print "The First Python Script On Server Side"
print "The sum of two numbers evaluation"
print "3+5 = ",3+5
我不知道出了什么问题。任何帮助将不胜感激!
【问题讨论】:
-
因为您显然是 Python 新手,所以在尝试深入研究 Web 编程(如 Dive into Python、Learning Python 或 Python for Dummies)之前,我会阅读一本关于一般 Python 编程的书。另外,如果我是你,我会使用完整的基于 WSGI 的 Web 框架,例如 Django 或 Flask,而不是 CGI。编程 CGI 很痛苦(相信我,我已经尝试过了)。如果您使用基于 WSGI 的框架,则更容易维护并且您可以在更多环境中运行您的应用程序。 CGI 在 Python 世界中几乎要走出来了。如果 CGI 是唯一可用的,您可以从 CGI 脚本运行 WSGI 应用程序。