Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Modules ที่จำเป็นสำหรับ CGI Programming ใน Python

โมดูล cgi ของ Python มักเป็นจุดเริ่มต้นในการเขียน CGI Programs ใน Python วัตถุประสงค์หลักของโมดูล cgi คือ Extract ค่าที่ส่งให้ CGI Program จาก HTML Form ส่วนใหญ่โต้ตอบกับ CGI Applications ผ่าน HTML Form ผู้ใช้กรอกค่าบางอย่างใน Form ที่ระบุรายละเอียดของ Action ที่จะทำ แล้วเรียก CGI ให้ทำ Action ตาม Specification

คุณอาจใส่ Input Fields หลายตัวใน HTML Form ซึ่งเป็นประเภทต่างๆ (Text, Checkboxes, Picklists, Radio Buttons, ฯลฯ)

Python Script ควรเริ่มด้วย import cgi สิ่งหลักที่ CGI Module ทำคือ จัดการ Fields ทั้งหมดใน Calling HTML Form แบบ Dictionary-like สิ่งที่ได้ไม่ใช่ Python Dictionary จริงๆ แต่ง่ายต่อการทำงาน ลองดูตัวอย่าง -

ตัวอย่าง

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'

เราจะต้องทำเพิ่มเติมเพื่อนำเสนอหน้าที่มีประโยชน์ให้ User แต่เราได้จุดเริ่มต้นที่ดีแล้วจากการทำงานกับ Form ที่ Submit มา