This module also defines functions that dump raw CGI environment information to
the browser (dumpstatepage), and that wrap calls to functions that print status messages
so that their output isn’t added to the HTML stream (runsilent). A version 3.0 addition
also attempts to work around the fact that built-in print calls can fail in Python 3.1 for
some types of Unicode text (e.g., non-ASCII character sets in Internationalized head-
ers), by forcing binary mode and bytes for the output stream (print).
I’ll leave the discovery of any remaining magic in the code in Example 16-14 up to you,
the reader. You are hereby admonished to go forth and read, refer, and reuse.
Example 16-14. PP4E\Internet\Web\PyMailCgi\cgi-bin\commonhtml.py
#!/usr/bin/python
"""
##################################################################################
generate standard page header, list, and footer HTML; isolates HTML generation
related details in this file; text printed here goes over a socket to the client,
to create parts of a new web page in the web browser; uses one print per line,
instead of string blocks; uses urllib to escape params in URL links auto from a
dict, but cgi.escape to put them in HTML hidden fields; some tools here may be
useful outside pymailcgi; could also return the HTML generated here instead of
printing it, so it could be included in other pages; could also structure as a
single CGI script that gets and tests a next action name as a hidden form field;
caveat: this system works, but was largely written during a two-hour layover at
the Chicago O'Hare airport: there is much room for improvement and optimization;
##################################################################################
"""
import cgi, urllib.parse, sys, os
3.0: Python 3.1 has issues printing some decoded str as text to stdout
import builtins
bstdout = open(sys.stdout.fileno(), 'wb')
def print(args, end='\n'):
try:
builtins.print(args, end=end)
sys.stdout.flush()
except:
for arg in args:
bstdout.write(str(arg).encode('utf-8'))
if end: bstdout.write(end.encode('utf-8'))
bstdout.flush()
sys.stderr = sys.stdout # show error messages in browser
from externs import mailconfig # from a package somewhere on server
from externs import mailtools # need parser for header decoding
parser = mailtools.MailParser() # one per process in this module
my cgi address root
#urlroot = 'http://starship.python.net/~lutz/PyMailCgi/'
#urlroot = 'http://localhost:8000/cgi-bin/'
urlroot = '' # use minimal, relative paths
Utility Modules | 1287