User:Emily/Prototyping/Trimester 03/03
HTTP server -- programs (CGI scripts) -- interface (user input submitted through HTML<form>or<isindex>element) --> generate web content
python -m CGIHTTPSever
structure of CGI
- web server, processes requests via HTTP (Hypertext Transfer Protocol)
- process user input submitted through an HTML <FORM> or <ISINDEX> element
- cgi_directories [' /cgi-bin', ' /htbin'] containing CGI scripts (server's special cgi-bin directory)
- output - CGI script consists of two sections, separated by a blank line.
print "Content-Type: text/html" # header, telling what kind of data is following (HTML is following) print # blank line, end of headers print "<TITLE>CGI script output</TITLE>" print "Hello Morld" #html, nice formatting
using cgi module
import cgitb cgitb.enable() # display detailed reports in web browser cgitb.enable(display=0, logdir="/path/to/logdir") #have the reports saved to files
= to get at submitted form data
FieldStorage class --> can be indexed like a Python dictionary (in operator; support the standard dictionary method keys(), and built-in function len())
form = cgi.FieldStorage()
the following code checks that the fields are set to a non-empty string
if "***" not in form or "###" not in form:
print "Error"
print "please fill in *** and ### fields"
return
print "<p>***:", form["***"].value
print "<p>###:", form["###"].value
if the submitted form data contains more than one field with the same name -->form[key] is not a FieldStorage or MiniFieldStorage instance but a list of such instances; form.getvalue(key) return a list of strings; getlist()method, always returns a list of values
value = form.getlist("username") usernames = ",".join(value)
If a field represents an uploaded file ????
fileitem = form["userfile"]
The appropriate way to read form data values was to always use the code which checks whether the obtained value is a single value or a list of values.
compact code:
import cgi
form = cgi.FieldStorage()
user = form.getfirst("user", "").upper() # This way it's safe.
for item in form.getlist("item"):
do_something(item)