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'

为了向用户展示有用的页面,我们需要做更多的工作,但是通过提交表单,我们已经有了一个良好的开端。