โมดูล cgi ของ Python มักจะเป็นจุดเริ่มต้นในการเขียนโปรแกรม CGI ใน Python วัตถุประสงค์หลักของโมดูล cgi คือการดึงค่าที่ส่งผ่านไปยังโปรแกรม CGI จากแบบฟอร์ม HTML ส่วนใหญ่โต้ตอบกับแอปพลิเคชัน CGI ผ่านแบบฟอร์ม HTML หนึ่งกรอกค่าบางค่าในแบบฟอร์มที่ระบุรายละเอียดของการดำเนินการที่จะดำเนินการ จากนั้นเรียก CGI ให้ดำเนินการโดยใช้ข้อกำหนดของคุณ
คุณอาจใส่ช่องป้อนข้อมูลจำนวนมากภายในแบบฟอร์ม HTML ซึ่งสามารถมีได้หลายประเภท (ข้อความ ช่องทำเครื่องหมาย รายการเลือก ปุ่มตัวเลือก ฯลฯ)
สคริปต์ Python ของคุณควรเริ่มต้นด้วยการนำเข้า 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' เราจะต้องทำมากกว่านี้เพื่อนำเสนอหน้าที่เป็นประโยชน์ต่อผู้ใช้ แต่เราเริ่มต้นได้ดีด้วยการทำงานกับแบบฟอร์มการส่ง