Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách xử lý dữ liệu form đơn giản bằng Python CGI script?

Giả sử có file HTML như sau:

<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>

Sau khi submit, form gửi đến getData.py để lấy dữ liệu và hiển thị. Code Python CGI:

#!C:\Python27\python.exe
import cgi, cgitb
form = cgi.FieldStorage()
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>")