A Python CGI Script
This post demonstrates using the cgi module in Python, and it is taken from this tutorial.
In a directory, write this html page and call it index.html
<html>
<head>
<title></title>
</head>
<body>
<form action ="/cgi-bin/hello_get.py" metho="get">
First Name: <input type="text" name="first_name"> <br />
Last Name: <input type="text" name="last_name" />
<input type ="submit" value="Submit" />
</form>
</body>
</html>
In a subdirectory cgi-bin
write the followinng file and call it hello_get.py
#!/usr/bin/python
# 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\r\n\r\n")
print("<html>")
print("<head>")
print("<title>Hello - Second CGI Program</title>")
print("</head>")
print("<body>")
print(f"<h2>Hello {first_name}, {last_name}</h2>")
print("</body>")
print("</html>")
Now turn out a webserver with
python -m http.server
and go to localhost:8000
in your browser. And that’s it, you can process form input.
What about linking it to a database like a proper web app? Flask, which I wrote about before.