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

วิธีประมวลผล Simple Form Data ด้วย Python CGI Script

สมมติมี HTML File ดังนี้ -

<form action="getData.py" method="post">
  FirstName: <input type="text" name="first_name">
  LastName: <input type="text" name="last_name">
  <input type="submit" value="go">
</form>

หลัง Submit Form จะไปที่ Python Page ชื่อ getData.py โดยต้องดึงข้อมูลจากหน้า HTML นี้และแสดง ต่อไปนี้คือโค้ดสำหรับ Python CGI

#!C:\Python27\python.exe
# Import modules for CGI handling
import cgi, cgitb

# Create instance of FieldStorage
form = cgi.FieldStorage()

# Get data from fields
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')

print("Content-type:text/html")
print()
print("<html>")
print("<head>")
print("<title>Hello - Second CGI Program</title>")
print("</head>")
print("<body>")
print(" Hello %s %s " % (first_name, last_name))
print("</body>")
print("</html>")