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'

我們必須做更多工作才能為使用者呈現一個有用的頁面,但我們已經透過一個提交表單的工作取得了一個良好的開端。

更新於: 16-6 月-2020

186 人瀏覽

開啟您的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.