Python CGI编程需要哪些模块?
Python 的 cgi 模块通常是 Python 中编写 CGI 程序的起点。cgi 模块的主要目的是从 HTML 表单中提取传递给 CGI 程序的值。大多数情况下,用户都是通过 HTML 表单与 CGI 应用程序进行交互。用户在表单中填写一些值来指定要执行的操作的细节,然后调用 CGI 使用用户的规格执行其操作。
你可以在 HTML 表单中包含许多输入字段,这些字段可以是多种不同类型(文本、复选框、选择列表、单选按钮等)。
你的 Python 脚本应该以 `import cgi` 开头。CGI 模块所做的主要事情是以类似字典的方式处理调用 HTML 表单中的所有字段。你得到的结果并不完全是 Python 字典,但它易于使用。让我们来看一个例子:
示例
import cgi
form = cgi.FieldStorage() # FieldStorage object to
# hold the form data
# check whether a field called "username" was used...
# it might be used multiple times (so sep w/ commas)
if form.has_key('username'):
username = form["username"]
usernames = ""
if type(username) is type([]):
# Multiple username fields specified
for item in username:
if usernames:
# Next item -- insert comma
usernames = usernames + "," + item.value
else:
# First item -- don't insert comma
usernames = item.value
else:
# Single username field specified
usernames = username.value
# just for the fun of it let's create an HTML list
# of all the fields on the calling form
field_list = '<ul>\n'
for field in form.keys():
field_list = field_list + '<li>%s</li>\n' % field
field_list = field_list + '</ul>\n'我们还需要做更多的事情才能向用户呈现一个有用的页面,但是我们已经通过处理提交表单取得了一个良好的开端。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP