home *** CD-ROM | disk | FTP | other *** search
/ linuxmafia.com 2016 / linuxmafia.com.tar / linuxmafia.com / pub / palmos / pippy-0.6beta-src.tar.gz / pippy-0.6beta-src.tar / pippy-0.6beta-src / src / Lib / cgi.py < prev    next >
Text File  |  2000-12-21  |  48KB  |  1,386 lines

  1. #! /usr/local/bin/python
  2.  
  3. """Support module for CGI (Common Gateway Interface) scripts.
  4.  
  5. This module defines a number of utilities for use by CGI scripts
  6. written in Python.
  7.  
  8.  
  9. Introduction
  10. ------------
  11.  
  12. A CGI script is invoked by an HTTP server, usually to process user
  13. input submitted through an HTML <FORM> or <ISINPUT> element.
  14.  
  15. Most often, CGI scripts live in the server's special cgi-bin
  16. directory.  The HTTP server places all sorts of information about the
  17. request (such as the client's hostname, the requested URL, the query
  18. string, and lots of other goodies) in the script's shell environment,
  19. executes the script, and sends the script's output back to the client.
  20.  
  21. The script's input is connected to the client too, and sometimes the
  22. form data is read this way; at other times the form data is passed via
  23. the "query string" part of the URL.  This module (cgi.py) is intended
  24. to take care of the different cases and provide a simpler interface to
  25. the Python script.  It also provides a number of utilities that help
  26. in debugging scripts, and the latest addition is support for file
  27. uploads from a form (if your browser supports it -- Grail 0.3 and
  28. Netscape 2.0 do).
  29.  
  30. The output of a CGI script should consist of two sections, separated
  31. by a blank line.  The first section contains a number of headers,
  32. telling the client what kind of data is following.  Python code to
  33. generate a minimal header section looks like this:
  34.  
  35.         print "Content-type: text/html" # HTML is following
  36.         print                           # blank line, end of headers
  37.  
  38. The second section is usually HTML, which allows the client software
  39. to display nicely formatted text with header, in-line images, etc.
  40. Here's Python code that prints a simple piece of HTML:
  41.  
  42.         print "<TITLE>CGI script output</TITLE>"
  43.         print "<H1>This is my first CGI script</H1>"
  44.         print "Hello, world!"
  45.  
  46. It may not be fully legal HTML according to the letter of the
  47. standard, but any browser will understand it.
  48.  
  49.  
  50. Using the cgi module
  51. --------------------
  52.  
  53. Begin by writing "import cgi".  Don't use "from cgi import *" -- the
  54. module defines all sorts of names for its own use or for backward 
  55. compatibility that you don't want in your namespace.
  56.  
  57. It's best to use the FieldStorage class.  The other classes define in this 
  58. module are provided mostly for backward compatibility.  Instantiate it 
  59. exactly once, without arguments.  This reads the form contents from 
  60. standard input or the environment (depending on the value of various 
  61. environment variables set according to the CGI standard).  Since it may 
  62. consume standard input, it should be instantiated only once.
  63.  
  64. The FieldStorage instance can be accessed as if it were a Python 
  65. dictionary.  For instance, the following code (which assumes that the 
  66. Content-type header and blank line have already been printed) checks that 
  67. the fields "name" and "addr" are both set to a non-empty string:
  68.  
  69.         form = cgi.FieldStorage()
  70.         form_ok = 0
  71.         if form.has_key("name") and form.has_key("addr"):
  72.                 if form["name"].value != "" and form["addr"].value != "":
  73.                         form_ok = 1
  74.         if not form_ok:
  75.                 print "<H1>Error</H1>"
  76.                 print "Please fill in the name and addr fields."
  77.                 return
  78.         ...further form processing here...
  79.  
  80. Here the fields, accessed through form[key], are themselves instances
  81. of FieldStorage (or MiniFieldStorage, depending on the form encoding).
  82.  
  83. If the submitted form data contains more than one field with the same
  84. name, the object retrieved by form[key] is not a (Mini)FieldStorage
  85. instance but a list of such instances.  If you are expecting this
  86. possibility (i.e., when your HTML form comtains multiple fields with
  87. the same name), use the type() function to determine whether you have
  88. a single instance or a list of instances.  For example, here's code
  89. that concatenates any number of username fields, separated by commas:
  90.  
  91.         username = form["username"]
  92.         if type(username) is type([]):
  93.                 # Multiple username fields specified
  94.                 usernames = ""
  95.                 for item in username:
  96.                         if usernames:
  97.                                 # Next item -- insert comma
  98.                                 usernames = usernames + "," + item.value
  99.                         else:
  100.                                 # First item -- don't insert comma
  101.                                 usernames = item.value
  102.         else:
  103.                 # Single username field specified
  104.                 usernames = username.value
  105.  
  106. If a field represents an uploaded file, the value attribute reads the 
  107. entire file in memory as a string.  This may not be what you want.  You can 
  108. test for an uploaded file by testing either the filename attribute or the 
  109. file attribute.  You can then read the data at leasure from the file 
  110. attribute:
  111.  
  112.         fileitem = form["userfile"]
  113.         if fileitem.file:
  114.                 # It's an uploaded file; count lines
  115.                 linecount = 0
  116.                 while 1:
  117.                         line = fileitem.file.readline()
  118.                         if not line: break
  119.                         linecount = linecount + 1
  120.  
  121. The file upload draft standard entertains the possibility of uploading
  122. multiple files from one field (using a recursive multipart/*
  123. encoding).  When this occurs, the item will be a dictionary-like
  124. FieldStorage item.  This can be determined by testing its type
  125. attribute, which should have the value "multipart/form-data" (or
  126. perhaps another string beginning with "multipart/").  It this case, it
  127. can be iterated over recursively just like the top-level form object.
  128.  
  129. When a form is submitted in the "old" format (as the query string or as a 
  130. single data part of type application/x-www-form-urlencoded), the items 
  131. will actually be instances of the class MiniFieldStorage.  In this case,
  132. the list, file and filename attributes are always None.
  133.  
  134.  
  135. Old classes
  136. -----------
  137.  
  138. These classes, present in earlier versions of the cgi module, are still 
  139. supported for backward compatibility.  New applications should use the
  140. FieldStorage class.
  141.  
  142. SvFormContentDict: single value form content as dictionary; assumes each 
  143. field name occurs in the form only once.
  144.  
  145. FormContentDict: multiple value form content as dictionary (the form
  146. items are lists of values).  Useful if your form contains multiple
  147. fields with the same name.
  148.  
  149. Other classes (FormContent, InterpFormContentDict) are present for
  150. backwards compatibility with really old applications only.  If you still 
  151. use these and would be inconvenienced when they disappeared from a next 
  152. version of this module, drop me a note.
  153.  
  154.  
  155. Functions
  156. ---------
  157.  
  158. These are useful if you want more control, or if you want to employ
  159. some of the algorithms implemented in this module in other
  160. circumstances.
  161.  
  162. parse(fp, [environ, [keep_blank_values, [strict_parsing]]]): parse a
  163. form into a Python dictionary.
  164.  
  165. parse_qs(qs, [keep_blank_values, [strict_parsing]]): parse a query
  166. string (data of type application/x-www-form-urlencoded).  Data are
  167. returned as a dictionary.  The dictionary keys are the unique query
  168. variable names and the values are lists of vales for each name.
  169.  
  170. parse_qsl(qs, [keep_blank_values, [strict_parsing]]): parse a query
  171. string (data of type application/x-www-form-urlencoded).  Data are
  172. returned as a list of (name, value) pairs.
  173.  
  174. parse_multipart(fp, pdict): parse input of type multipart/form-data (for 
  175. file uploads).
  176.  
  177. parse_header(string): parse a header like Content-type into a main
  178. value and a dictionary of parameters.
  179.  
  180. test(): complete test program.
  181.  
  182. print_environ(): format the shell environment in HTML.
  183.  
  184. print_form(form): format a form in HTML.
  185.  
  186. print_environ_usage(): print a list of useful environment variables in
  187. HTML.
  188.  
  189. escape(): convert the characters "&", "<" and ">" to HTML-safe
  190. sequences.  Use this if you need to display text that might contain
  191. such characters in HTML.  To translate URLs for inclusion in the HREF
  192. attribute of an <A> tag, use urllib.quote().
  193.  
  194. log(fmt, ...): write a line to a log file; see docs for initlog().
  195.  
  196.  
  197. Caring about security
  198. ---------------------
  199.  
  200. There's one important rule: if you invoke an external program (e.g.
  201. via the os.system() or os.popen() functions), make very sure you don't
  202. pass arbitrary strings received from the client to the shell.  This is
  203. a well-known security hole whereby clever hackers anywhere on the web
  204. can exploit a gullible CGI script to invoke arbitrary shell commands.
  205. Even parts of the URL or field names cannot be trusted, since the
  206. request doesn't have to come from your form!
  207.  
  208. To be on the safe side, if you must pass a string gotten from a form
  209. to a shell command, you should make sure the string contains only
  210. alphanumeric characters, dashes, underscores, and periods.
  211.  
  212.  
  213. Installing your CGI script on a Unix system
  214. -------------------------------------------
  215.  
  216. Read the documentation for your HTTP server and check with your local
  217. system administrator to find the directory where CGI scripts should be
  218. installed; usually this is in a directory cgi-bin in the server tree.
  219.  
  220. Make sure that your script is readable and executable by "others"; the
  221. Unix file mode should be 755 (use "chmod 755 filename").  Make sure
  222. that the first line of the script contains #! starting in column 1
  223. followed by the pathname of the Python interpreter, for instance:
  224.  
  225.         #! /usr/local/bin/python
  226.  
  227. Make sure the Python interpreter exists and is executable by "others".
  228.  
  229. Note that it's probably not a good idea to use #! /usr/bin/env python
  230. here, since the Python interpreter may not be on the default path
  231. given to CGI scripts!!!
  232.  
  233. Make sure that any files your script needs to read or write are
  234. readable or writable, respectively, by "others" -- their mode should
  235. be 644 for readable and 666 for writable.  This is because, for
  236. security reasons, the HTTP server executes your script as user
  237. "nobody", without any special privileges.  It can only read (write,
  238. execute) files that everybody can read (write, execute).  The current
  239. directory at execution time is also different (it is usually the
  240. server's cgi-bin directory) and the set of environment variables is
  241. also different from what you get at login.  in particular, don't count
  242. on the shell's search path for executables ($PATH) or the Python
  243. module search path ($PYTHONPATH) to be set to anything interesting.
  244.  
  245. If you need to load modules from a directory which is not on Python's
  246. default module search path, you can change the path in your script,
  247. before importing other modules, e.g.:
  248.  
  249.         import sys
  250.         sys.path.insert(0, "/usr/home/joe/lib/python")
  251.         sys.path.insert(0, "/usr/local/lib/python")
  252.  
  253. This way, the directory inserted last will be searched first!
  254.  
  255. Instructions for non-Unix systems will vary; check your HTTP server's
  256. documentation (it will usually have a section on CGI scripts).
  257.  
  258.  
  259. Testing your CGI script
  260. -----------------------
  261.  
  262. Unfortunately, a CGI script will generally not run when you try it
  263. from the command line, and a script that works perfectly from the
  264. command line may fail mysteriously when run from the server.  There's
  265. one reason why you should still test your script from the command
  266. line: if it contains a syntax error, the python interpreter won't
  267. execute it at all, and the HTTP server will most likely send a cryptic
  268. error to the client.
  269.  
  270. Assuming your script has no syntax errors, yet it does not work, you
  271. have no choice but to read the next section:
  272.  
  273.  
  274. Debugging CGI scripts
  275. ---------------------
  276.  
  277. First of all, check for trivial installation errors -- reading the
  278. section above on installing your CGI script carefully can save you a
  279. lot of time.  If you wonder whether you have understood the
  280. installation procedure correctly, try installing a copy of this module
  281. file (cgi.py) as a CGI script.  When invoked as a script, the file
  282. will dump its environment and the contents of the form in HTML form.
  283. Give it the right mode etc, and send it a request.  If it's installed
  284. in the standard cgi-bin directory, it should be possible to send it a
  285. request by entering a URL into your browser of the form:
  286.  
  287.         http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home
  288.  
  289. If this gives an error of type 404, the server cannot find the script
  290. -- perhaps you need to install it in a different directory.  If it
  291. gives another error (e.g.  500), there's an installation problem that
  292. you should fix before trying to go any further.  If you get a nicely
  293. formatted listing of the environment and form content (in this
  294. example, the fields should be listed as "addr" with value "At Home"
  295. and "name" with value "Joe Blow"), the cgi.py script has been
  296. installed correctly.  If you follow the same procedure for your own
  297. script, you should now be able to debug it.
  298.  
  299. The next step could be to call the cgi module's test() function from
  300. your script: replace its main code with the single statement
  301.  
  302.         cgi.test()
  303.         
  304. This should produce the same results as those gotten from installing
  305. the cgi.py file itself.
  306.  
  307. When an ordinary Python script raises an unhandled exception (e.g.,
  308. because of a typo in a module name, a file that can't be opened,
  309. etc.), the Python interpreter prints a nice traceback and exits.
  310. While the Python interpreter will still do this when your CGI script
  311. raises an exception, most likely the traceback will end up in one of
  312. the HTTP server's log file, or be discarded altogether.
  313.  
  314. Fortunately, once you have managed to get your script to execute
  315. *some* code, it is easy to catch exceptions and cause a traceback to
  316. be printed.  The test() function below in this module is an example.
  317. Here are the rules:
  318.  
  319.         1. Import the traceback module (before entering the
  320.            try-except!)
  321.         
  322.         2. Make sure you finish printing the headers and the blank
  323.            line early
  324.         
  325.         3. Assign sys.stderr to sys.stdout
  326.         
  327.         3. Wrap all remaining code in a try-except statement
  328.         
  329.         4. In the except clause, call traceback.print_exc()
  330.  
  331. For example:
  332.  
  333.         import sys
  334.         import traceback
  335.         print "Content-type: text/html"
  336.         print
  337.         sys.stderr = sys.stdout
  338.         try:
  339.                 ...your code here...
  340.         except:
  341.                 print "\n\n<PRE>"
  342.                 traceback.print_exc()
  343.  
  344. Notes: The assignment to sys.stderr is needed because the traceback
  345. prints to sys.stderr.  The print "\n\n<PRE>" statement is necessary to
  346. disable the word wrapping in HTML.
  347.  
  348. If you suspect that there may be a problem in importing the traceback
  349. module, you can use an even more robust approach (which only uses
  350. built-in modules):
  351.  
  352.         import sys
  353.         sys.stderr = sys.stdout
  354.         print "Content-type: text/plain"
  355.         print
  356.         ...your code here...
  357.  
  358. This relies on the Python interpreter to print the traceback.  The
  359. content type of the output is set to plain text, which disables all
  360. HTML processing.  If your script works, the raw HTML will be displayed
  361. by your client.  If it raises an exception, most likely after the
  362. first two lines have been printed, a traceback will be displayed.
  363. Because no HTML interpretation is going on, the traceback will
  364. readable.
  365.  
  366. When all else fails, you may want to insert calls to log() to your
  367. program or even to a copy of the cgi.py file.  Note that this requires
  368. you to set cgi.logfile to the name of a world-writable file before the
  369. first call to log() is made!
  370.  
  371. Good luck!
  372.  
  373.  
  374. Common problems and solutions
  375. -----------------------------
  376.  
  377. - Most HTTP servers buffer the output from CGI scripts until the
  378. script is completed.  This means that it is not possible to display a
  379. progress report on the client's display while the script is running.
  380.  
  381. - Check the installation instructions above.
  382.  
  383. - Check the HTTP server's log files.  ("tail -f logfile" in a separate
  384. window may be useful!)
  385.  
  386. - Always check a script for syntax errors first, by doing something
  387. like "python script.py".
  388.  
  389. - When using any of the debugging techniques, don't forget to add
  390. "import sys" to the top of the script.
  391.  
  392. - When invoking external programs, make sure they can be found.
  393. Usually, this means using absolute path names -- $PATH is usually not
  394. set to a very useful value in a CGI script.
  395.  
  396. - When reading or writing external files, make sure they can be read
  397. or written by every user on the system.
  398.  
  399. - Don't try to give a CGI script a set-uid mode.  This doesn't work on
  400. most systems, and is a security liability as well.
  401.  
  402. """
  403.  
  404. # XXX The module is getting pretty heavy with all those docstrings.
  405. # Perhaps there should be a slimmed version that doesn't contain all those 
  406. # backwards compatible and debugging classes and functions?
  407.  
  408. # History
  409. # -------
  410. # Michael McLay started this module.  Steve Majewski changed the
  411. # interface to SvFormContentDict and FormContentDict.  The multipart
  412. # parsing was inspired by code submitted by Andreas Paepcke.  Guido van
  413. # Rossum rewrote, reformatted and documented the module and is currently
  414. # responsible for its maintenance.
  415.  
  416. __version__ = "2.2"
  417.  
  418.  
  419. # Imports
  420. # =======
  421.  
  422. import string
  423. import sys
  424. import os
  425. import urllib
  426. import mimetools
  427. import rfc822
  428. from StringIO import StringIO
  429.  
  430.  
  431. # Logging support
  432. # ===============
  433.  
  434. logfile = ""            # Filename to log to, if not empty
  435. logfp = None            # File object to log to, if not None
  436.  
  437. def initlog(*allargs):
  438.     """Write a log message, if there is a log file.
  439.  
  440.     Even though this function is called initlog(), you should always
  441.     use log(); log is a variable that is set either to initlog
  442.     (initially), to dolog (once the log file has been opened), or to
  443.     nolog (when logging is disabled).
  444.  
  445.     The first argument is a format string; the remaining arguments (if
  446.     any) are arguments to the % operator, so e.g.
  447.         log("%s: %s", "a", "b")
  448.     will write "a: b" to the log file, followed by a newline.
  449.  
  450.     If the global logfp is not None, it should be a file object to
  451.     which log data is written.
  452.  
  453.     If the global logfp is None, the global logfile may be a string
  454.     giving a filename to open, in append mode.  This file should be
  455.     world writable!!!  If the file can't be opened, logging is
  456.     silently disabled (since there is no safe place where we could
  457.     send an error message).
  458.  
  459.     """
  460.     global logfp, log
  461.     if logfile and not logfp:
  462.         try:
  463.             logfp = open(logfile, "a")
  464.         except IOError:
  465.             pass
  466.     if not logfp:
  467.         log = nolog
  468.     else:
  469.         log = dolog
  470.     apply(log, allargs)
  471.  
  472. def dolog(fmt, *args):
  473.     """Write a log message to the log file.  See initlog() for docs."""
  474.     logfp.write(fmt%args + "\n")
  475.  
  476. def nolog(*allargs):
  477.     """Dummy function, assigned to log when logging is disabled."""
  478.     pass
  479.  
  480. log = initlog           # The current logging function
  481.  
  482.  
  483. # Parsing functions
  484. # =================
  485.  
  486. # Maximum input we will accept when REQUEST_METHOD is POST
  487. # 0 ==> unlimited input
  488. maxlen = 0
  489.  
  490. def parse(fp=None, environ=os.environ, keep_blank_values=0, strict_parsing=0):
  491.     """Parse a query in the environment or from a file (default stdin)
  492.  
  493.         Arguments, all optional:
  494.  
  495.         fp              : file pointer; default: sys.stdin
  496.  
  497.         environ         : environment dictionary; default: os.environ
  498.  
  499.         keep_blank_values: flag indicating whether blank values in
  500.             URL encoded forms should be treated as blank strings.  
  501.             A true value inicates that blanks should be retained as 
  502.             blank strings.  The default false value indicates that
  503.             blank values are to be ignored and treated as if they were
  504.             not included.
  505.  
  506.         strict_parsing: flag indicating what to do with parsing errors.
  507.             If false (the default), errors are silently ignored.
  508.             If true, errors raise a ValueError exception.
  509.     """
  510.     if not fp:
  511.         fp = sys.stdin
  512.     if not environ.has_key('REQUEST_METHOD'):
  513.         environ['REQUEST_METHOD'] = 'GET'       # For testing stand-alone
  514.     if environ['REQUEST_METHOD'] == 'POST':
  515.         ctype, pdict = parse_header(environ['CONTENT_TYPE'])
  516.         if ctype == 'multipart/form-data':
  517.             return parse_multipart(fp, pdict)
  518.         elif ctype == 'application/x-www-form-urlencoded':
  519.             clength = string.atoi(environ['CONTENT_LENGTH'])
  520.             if maxlen and clength > maxlen:
  521.                 raise ValueError, 'Maximum content length exceeded'
  522.             qs = fp.read(clength)
  523.         else:
  524.             qs = ''                     # Unknown content-type
  525.         if environ.has_key('QUERY_STRING'): 
  526.             if qs: qs = qs + '&'
  527.             qs = qs + environ['QUERY_STRING']
  528.         elif sys.argv[1:]: 
  529.             if qs: qs = qs + '&'
  530.             qs = qs + sys.argv[1]
  531.         environ['QUERY_STRING'] = qs    # XXX Shouldn't, really
  532.     elif environ.has_key('QUERY_STRING'):
  533.         qs = environ['QUERY_STRING']
  534.     else:
  535.         if sys.argv[1:]:
  536.             qs = sys.argv[1]
  537.         else:
  538.             qs = ""
  539.         environ['QUERY_STRING'] = qs    # XXX Shouldn't, really
  540.     return parse_qs(qs, keep_blank_values, strict_parsing)
  541.  
  542.  
  543. def parse_qs(qs, keep_blank_values=0, strict_parsing=0):
  544.     """Parse a query given as a string argument.
  545.  
  546.         Arguments:
  547.  
  548.         qs: URL-encoded query string to be parsed
  549.  
  550.         keep_blank_values: flag indicating whether blank values in
  551.             URL encoded queries should be treated as blank strings.  
  552.             A true value inicates that blanks should be retained as 
  553.             blank strings.  The default false value indicates that
  554.             blank values are to be ignored and treated as if they were
  555.             not included.
  556.  
  557.         strict_parsing: flag indicating what to do with parsing errors.
  558.             If false (the default), errors are silently ignored.
  559.             If true, errors raise a ValueError exception.
  560.     """
  561.     dict = {}
  562.     for name, value in parse_qsl(qs, keep_blank_values, strict_parsing):
  563.         if len(value) or keep_blank_values:
  564.             if dict.has_key(name):
  565.                 dict[name].append(value)
  566.             else:
  567.                 dict[name] = [value]
  568.     return dict
  569.  
  570. def parse_qsl(qs, keep_blank_values=0, strict_parsing=0):
  571.     """Parse a query given as a string argument.
  572.  
  573.         Arguments:
  574.  
  575.         qs: URL-encoded query string to be parsed
  576.  
  577.         keep_blank_values: flag indicating whether blank values in
  578.             URL encoded queries should be treated as blank strings.  
  579.             A true value inicates that blanks should be retained as 
  580.             blank strings.  The default false value indicates that
  581.             blank values are to be ignored and treated as if they were
  582.             not included.
  583.  
  584.         strict_parsing: flag indicating what to do with parsing errors.
  585.             If false (the default), errors are silently ignored.
  586.             If true, errors raise a ValueError exception.
  587.  
  588.        Returns a list, as God intended.
  589.     """
  590.     name_value_pairs = string.splitfields(qs, '&')
  591.     r=[]
  592.     for name_value in name_value_pairs:
  593.         nv = string.splitfields(name_value, '=')
  594.         if len(nv) != 2:
  595.             if strict_parsing:
  596.                 raise ValueError, "bad query field: %s" % `name_value`
  597.             continue
  598.         name = urllib.unquote(string.replace(nv[0], '+', ' '))
  599.         value = urllib.unquote(string.replace(nv[1], '+', ' '))
  600.         r.append((name, value))
  601.  
  602.     return r
  603.  
  604.  
  605. def parse_multipart(fp, pdict):
  606.     """Parse multipart input.
  607.  
  608.     Arguments:
  609.     fp   : input file
  610.     pdict: dictionary containing other parameters of conten-type header
  611.  
  612.     Returns a dictionary just like parse_qs(): keys are the field names, each 
  613.     value is a list of values for that field.  This is easy to use but not 
  614.     much good if you are expecting megabytes to be uploaded -- in that case, 
  615.     use the FieldStorage class instead which is much more flexible.  Note 
  616.     that content-type is the raw, unparsed contents of the content-type 
  617.     header.
  618.     
  619.     XXX This does not parse nested multipart parts -- use FieldStorage for 
  620.     that.
  621.     
  622.     XXX This should really be subsumed by FieldStorage altogether -- no 
  623.     point in having two implementations of the same parsing algorithm.
  624.  
  625.     """
  626.     if pdict.has_key('boundary'):
  627.         boundary = pdict['boundary']
  628.     else:
  629.         boundary = ""
  630.     nextpart = "--" + boundary
  631.     lastpart = "--" + boundary + "--"
  632.     partdict = {}
  633.     terminator = ""
  634.  
  635.     while terminator != lastpart:
  636.         bytes = -1
  637.         data = None
  638.         if terminator:
  639.             # At start of next part.  Read headers first.
  640.             headers = mimetools.Message(fp)
  641.             clength = headers.getheader('content-length')
  642.             if clength:
  643.                 try:
  644.                     bytes = string.atoi(clength)
  645.                 except string.atoi_error:
  646.                     pass
  647.             if bytes > 0:
  648.                 if maxlen and bytes > maxlen:
  649.                     raise ValueError, 'Maximum content length exceeded'
  650.                 data = fp.read(bytes)
  651.             else:
  652.                 data = ""
  653.         # Read lines until end of part.
  654.         lines = []
  655.         while 1:
  656.             line = fp.readline()
  657.             if not line:
  658.                 terminator = lastpart # End outer loop
  659.                 break
  660.             if line[:2] == "--":
  661.                 terminator = string.strip(line)
  662.                 if terminator in (nextpart, lastpart):
  663.                     break
  664.             lines.append(line)
  665.         # Done with part.
  666.         if data is None:
  667.             continue
  668.         if bytes < 0:
  669.             if lines:
  670.                 # Strip final line terminator
  671.                 line = lines[-1]
  672.                 if line[-2:] == "\r\n":
  673.                     line = line[:-2]
  674.                 elif line[-1:] == "\n":
  675.                     line = line[:-1]
  676.                 lines[-1] = line
  677.                 data = string.joinfields(lines, "")
  678.         line = headers['content-disposition']
  679.         if not line:
  680.             continue
  681.         key, params = parse_header(line)
  682.         if key != 'form-data':
  683.             continue
  684.         if params.has_key('name'):
  685.             name = params['name']
  686.         else:
  687.             continue
  688.         if partdict.has_key(name):
  689.             partdict[name].append(data)
  690.         else:
  691.             partdict[name] = [data]
  692.  
  693.     return partdict
  694.  
  695.  
  696. def parse_header(line):
  697.     """Parse a Content-type like header.
  698.  
  699.     Return the main content-type and a dictionary of options.
  700.  
  701.     """
  702.     plist = map(string.strip, string.splitfields(line, ';'))
  703.     key = string.lower(plist[0])
  704.     del plist[0]
  705.     pdict = {}
  706.     for p in plist:
  707.         i = string.find(p, '=')
  708.         if i >= 0:
  709.             name = string.lower(string.strip(p[:i]))
  710.             value = string.strip(p[i+1:])
  711.             if len(value) >= 2 and value[0] == value[-1] == '"':
  712.                 value = value[1:-1]
  713.             pdict[name] = value
  714.     return key, pdict
  715.  
  716.  
  717. # Classes for field storage
  718. # =========================
  719.  
  720. class MiniFieldStorage:
  721.  
  722.     """Like FieldStorage, for use when no file uploads are possible."""
  723.  
  724.     # Dummy attributes
  725.     filename = None
  726.     list = None
  727.     type = None
  728.     file = None
  729.     type_options = {}
  730.     disposition = None
  731.     disposition_options = {}
  732.     headers = {}
  733.  
  734.     def __init__(self, name, value):
  735.         """Constructor from field name and value."""
  736.         self.name = name
  737.         self.value = value
  738.         # self.file = StringIO(value)
  739.  
  740.     def __repr__(self):
  741.         """Return printable representation."""
  742.         return "MiniFieldStorage(%s, %s)" % (`self.name`, `self.value`)
  743.  
  744.  
  745. class FieldStorage:
  746.  
  747.     """Store a sequence of fields, reading multipart/form-data.
  748.  
  749.     This class provides naming, typing, files stored on disk, and
  750.     more.  At the top level, it is accessible like a dictionary, whose
  751.     keys are the field names.  (Note: None can occur as a field name.)
  752.     The items are either a Python list (if there's multiple values) or
  753.     another FieldStorage or MiniFieldStorage object.  If it's a single
  754.     object, it has the following attributes:
  755.  
  756.     name: the field name, if specified; otherwise None
  757.  
  758.     filename: the filename, if specified; otherwise None; this is the
  759.         client side filename, *not* the file name on which it is
  760.         stored (that's a temporary file you don't deal with)
  761.  
  762.     value: the value as a *string*; for file uploads, this
  763.         transparently reads the file every time you request the value
  764.  
  765.     file: the file(-like) object from which you can read the data;
  766.         None if the data is stored a simple string
  767.  
  768.     type: the content-type, or None if not specified
  769.  
  770.     type_options: dictionary of options specified on the content-type
  771.         line
  772.  
  773.     disposition: content-disposition, or None if not specified
  774.  
  775.     disposition_options: dictionary of corresponding options
  776.  
  777.     headers: a dictionary(-like) object (sometimes rfc822.Message or a
  778.         subclass thereof) containing *all* headers
  779.  
  780.     The class is subclassable, mostly for the purpose of overriding
  781.     the make_file() method, which is called internally to come up with
  782.     a file open for reading and writing.  This makes it possible to
  783.     override the default choice of storing all files in a temporary
  784.     directory and unlinking them as soon as they have been opened.
  785.  
  786.     """
  787.  
  788.     def __init__(self, fp=None, headers=None, outerboundary="",
  789.                  environ=os.environ, keep_blank_values=0, strict_parsing=0):
  790.         """Constructor.  Read multipart/* until last part.
  791.  
  792.         Arguments, all optional:
  793.  
  794.         fp              : file pointer; default: sys.stdin
  795.             (not used when the request method is GET)
  796.  
  797.         headers         : header dictionary-like object; default:
  798.             taken from environ as per CGI spec
  799.  
  800.         outerboundary   : terminating multipart boundary
  801.             (for internal use only)
  802.  
  803.         environ         : environment dictionary; default: os.environ
  804.  
  805.         keep_blank_values: flag indicating whether blank values in
  806.             URL encoded forms should be treated as blank strings.  
  807.             A true value inicates that blanks should be retained as 
  808.             blank strings.  The default false value indicates that
  809.             blank values are to be ignored and treated as if they were
  810.             not included.
  811.  
  812.         strict_parsing: flag indicating what to do with parsing errors.
  813.             If false (the default), errors are silently ignored.
  814.             If true, errors raise a ValueError exception.
  815.  
  816.         """
  817.         method = 'GET'
  818.         self.keep_blank_values = keep_blank_values
  819.         self.strict_parsing = strict_parsing
  820.         if environ.has_key('REQUEST_METHOD'):
  821.             method = string.upper(environ['REQUEST_METHOD'])
  822.         if method == 'GET' or method == 'HEAD':
  823.             if environ.has_key('QUERY_STRING'):
  824.                 qs = environ['QUERY_STRING']
  825.             elif sys.argv[1:]:
  826.                 qs = sys.argv[1]
  827.             else:
  828.                 qs = ""
  829.             fp = StringIO(qs)
  830.             if headers is None:
  831.                 headers = {'content-type':
  832.                            "application/x-www-form-urlencoded"}
  833.         if headers is None:
  834.             headers = {}
  835.             if method == 'POST':
  836.                 # Set default content-type for POST to what's traditional
  837.                 headers['content-type'] = "application/x-www-form-urlencoded"
  838.             if environ.has_key('CONTENT_TYPE'):
  839.                 headers['content-type'] = environ['CONTENT_TYPE']
  840.             if environ.has_key('CONTENT_LENGTH'):
  841.                 headers['content-length'] = environ['CONTENT_LENGTH']
  842.         self.fp = fp or sys.stdin
  843.         self.headers = headers
  844.         self.outerboundary = outerboundary
  845.  
  846.         # Process content-disposition header
  847.         cdisp, pdict = "", {}
  848.         if self.headers.has_key('content-disposition'):
  849.             cdisp, pdict = parse_header(self.headers['content-disposition'])
  850.         self.disposition = cdisp
  851.         self.disposition_options = pdict
  852.         self.name = None
  853.         if pdict.has_key('name'):
  854.             self.name = pdict['name']
  855.         self.filename = None
  856.         if pdict.has_key('filename'):
  857.             self.filename = pdict['filename']
  858.  
  859.         # Process content-type header
  860.         #
  861.         # Honor any existing content-type header.  But if there is no
  862.         # content-type header, use some sensible defaults.  Assume
  863.         # outerboundary is "" at the outer level, but something non-false
  864.         # inside a multi-part.  The default for an inner part is text/plain,
  865.         # but for an outer part it should be urlencoded.  This should catch
  866.         # bogus clients which erroneously forget to include a content-type
  867.         # header.
  868.         #
  869.         # See below for what we do if there does exist a content-type header,
  870.         # but it happens to be something we don't understand.
  871.         if self.headers.has_key('content-type'):
  872.             ctype, pdict = parse_header(self.headers['content-type'])
  873.         elif self.outerboundary or method != 'POST':
  874.             ctype, pdict = "text/plain", {}
  875.         else:
  876.             ctype, pdict = 'application/x-www-form-urlencoded', {}
  877.         self.type = ctype
  878.         self.type_options = pdict
  879.         self.innerboundary = ""
  880.         if pdict.has_key('boundary'):
  881.             self.innerboundary = pdict['boundary']
  882.         clen = -1
  883.         if self.headers.has_key('content-length'):
  884.             try:
  885.                 clen = string.atoi(self.headers['content-length'])
  886.             except:
  887.                 pass
  888.             if maxlen and clen > maxlen:
  889.                 raise ValueError, 'Maximum content length exceeded'
  890.         self.length = clen
  891.  
  892.         self.list = self.file = None
  893.         self.done = 0
  894.         self.lines = []
  895.         if ctype == 'application/x-www-form-urlencoded':
  896.             self.read_urlencoded()
  897.         elif ctype[:10] == 'multipart/':
  898.             self.read_multi(environ, keep_blank_values, strict_parsing)
  899.         else:
  900.             self.read_single()
  901.  
  902.     def __repr__(self):
  903.         """Return a printable representation."""
  904.         return "FieldStorage(%s, %s, %s)" % (
  905.                 `self.name`, `self.filename`, `self.value`)
  906.  
  907.     def __getattr__(self, name):
  908.         if name != 'value':
  909.             raise AttributeError, name
  910.         if self.file:
  911.             self.file.seek(0)
  912.             value = self.file.read()
  913.             self.file.seek(0)
  914.         elif self.list is not None:
  915.             value = self.list
  916.         else:
  917.             value = None
  918.         return value
  919.  
  920.     def __getitem__(self, key):
  921.         """Dictionary style indexing."""
  922.         if self.list is None:
  923.             raise TypeError, "not indexable"
  924.         found = []
  925.         for item in self.list:
  926.             if item.name == key: found.append(item)
  927.         if not found:
  928.             raise KeyError, key
  929.         if len(found) == 1:
  930.             return found[0]
  931.         else:
  932.             return found
  933.  
  934.     def keys(self):
  935.         """Dictionary style keys() method."""
  936.         if self.list is None:
  937.             raise TypeError, "not indexable"
  938.         keys = []
  939.         for item in self.list:
  940.             if item.name not in keys: keys.append(item.name)
  941.         return keys
  942.  
  943.     def has_key(self, key):
  944.         """Dictionary style has_key() method."""
  945.         if self.list is None:
  946.             raise TypeError, "not indexable"
  947.         for item in self.list:
  948.             if item.name == key: return 1
  949.         return 0
  950.  
  951.     def __len__(self):
  952.         """Dictionary style len(x) support."""
  953.         return len(self.keys())
  954.  
  955.     def read_urlencoded(self):
  956.         """Internal: read data in query string format."""
  957.         qs = self.fp.read(self.length)
  958.         self.list = list = []
  959.         for key, value in parse_qsl(qs, self.keep_blank_values,
  960.                                     self.strict_parsing):
  961.             list.append(MiniFieldStorage(key, value))
  962.         self.skip_lines()
  963.  
  964.     FieldStorageClass = None
  965.  
  966.     def read_multi(self, environ, keep_blank_values, strict_parsing):
  967.         """Internal: read a part that is itself multipart."""
  968.         self.list = []
  969.         klass = self.FieldStorageClass or self.__class__
  970.         part = klass(self.fp, {}, self.innerboundary,
  971.                      environ, keep_blank_values, strict_parsing)
  972.         # Throw first part away
  973.         while not part.done:
  974.             headers = rfc822.Message(self.fp)
  975.             part = klass(self.fp, headers, self.innerboundary,
  976.                          environ, keep_blank_values, strict_parsing)
  977.             self.list.append(part)
  978.         self.skip_lines()
  979.  
  980.     def read_single(self):
  981.         """Internal: read an atomic part."""
  982.         if self.length >= 0:
  983.             self.read_binary()
  984.             self.skip_lines()
  985.         else:
  986.             self.read_lines()
  987.         self.file.seek(0)
  988.  
  989.     bufsize = 8*1024            # I/O buffering size for copy to file
  990.  
  991.     def read_binary(self):
  992.         """Internal: read binary data."""
  993.         self.file = self.make_file('b')
  994.         todo = self.length
  995.         if todo >= 0:
  996.             while todo > 0:
  997.                 data = self.fp.read(min(todo, self.bufsize))
  998.                 if not data:
  999.                     self.done = -1
  1000.                     break
  1001.                 self.file.write(data)
  1002.                 todo = todo - len(data)
  1003.  
  1004.     def read_lines(self):
  1005.         """Internal: read lines until EOF or outerboundary."""
  1006.         self.file = self.make_file('')
  1007.         if self.outerboundary:
  1008.             self.read_lines_to_outerboundary()
  1009.         else:
  1010.             self.read_lines_to_eof()
  1011.  
  1012.     def read_lines_to_eof(self):
  1013.         """Internal: read lines until EOF."""
  1014.         while 1:
  1015.             line = self.fp.readline()
  1016.             if not line:
  1017.                 self.done = -1
  1018.                 break
  1019.             self.lines.append(line)
  1020.             self.file.write(line)
  1021.  
  1022.     def read_lines_to_outerboundary(self):
  1023.         """Internal: read lines until outerboundary."""
  1024.         next = "--" + self.outerboundary
  1025.         last = next + "--"
  1026.         delim = ""
  1027.         while 1:
  1028.             line = self.fp.readline()
  1029.             if not line:
  1030.                 self.done = -1
  1031.                 break
  1032.             self.lines.append(line)
  1033.             if line[:2] == "--":
  1034.                 strippedline = string.strip(line)
  1035.                 if strippedline == next:
  1036.                     break
  1037.                 if strippedline == last:
  1038.                     self.done = 1
  1039.                     break
  1040.             odelim = delim
  1041.             if line[-2:] == "\r\n":
  1042.                 delim = "\r\n"
  1043.                 line = line[:-2]
  1044.             elif line[-1] == "\n":
  1045.                 delim = "\n"
  1046.                 line = line[:-1]
  1047.             else:
  1048.                 delim = ""
  1049.             self.file.write(odelim + line)
  1050.  
  1051.     def skip_lines(self):
  1052.         """Internal: skip lines until outer boundary if defined."""
  1053.         if not self.outerboundary or self.done:
  1054.             return
  1055.         next = "--" + self.outerboundary
  1056.         last = next + "--"
  1057.         while 1:
  1058.             line = self.fp.readline()
  1059.             if not line:
  1060.                 self.done = -1
  1061.                 break
  1062.             self.lines.append(line)
  1063.             if line[:2] == "--":
  1064.                 strippedline = string.strip(line)
  1065.                 if strippedline == next:
  1066.                     break
  1067.                 if strippedline == last:
  1068.                     self.done = 1
  1069.                     break
  1070.  
  1071.     def make_file(self, binary=None):
  1072.         """Overridable: return a readable & writable file.
  1073.  
  1074.         The file will be used as follows:
  1075.         - data is written to it
  1076.         - seek(0)
  1077.         - data is read from it
  1078.  
  1079.         The 'binary' argument is unused -- the file is always opened
  1080.         in binary mode.
  1081.  
  1082.         This version opens a temporary file for reading and writing,
  1083.         and immediately deletes (unlinks) it.  The trick (on Unix!) is
  1084.         that the file can still be used, but it can't be opened by
  1085.         another process, and it will automatically be deleted when it
  1086.         is closed or when the current process terminates.
  1087.  
  1088.         If you want a more permanent file, you derive a class which
  1089.         overrides this method.  If you want a visible temporary file
  1090.         that is nevertheless automatically deleted when the script
  1091.         terminates, try defining a __del__ method in a derived class
  1092.         which unlinks the temporary files you have created.
  1093.  
  1094.         """
  1095.         import tempfile
  1096.         return tempfile.TemporaryFile("w+b")
  1097.         
  1098.  
  1099.  
  1100. # Backwards Compatibility Classes
  1101. # ===============================
  1102.  
  1103. class FormContentDict:
  1104.     """Basic (multiple values per field) form content as dictionary.
  1105.  
  1106.     form = FormContentDict()
  1107.  
  1108.     form[key] -> [value, value, ...]
  1109.     form.has_key(key) -> Boolean
  1110.     form.keys() -> [key, key, ...]
  1111.     form.values() -> [[val, val, ...], [val, val, ...], ...]
  1112.     form.items() ->  [(key, [val, val, ...]), (key, [val, val, ...]), ...]
  1113.     form.dict == {key: [val, val, ...], ...}
  1114.  
  1115.     """
  1116.     def __init__(self, environ=os.environ):
  1117.         self.dict = parse(environ=environ)
  1118.         self.query_string = environ['QUERY_STRING']
  1119.     def __getitem__(self,key):
  1120.         return self.dict[key]
  1121.     def keys(self):
  1122.         return self.dict.keys()
  1123.     def has_key(self, key):
  1124.         return self.dict.has_key(key)
  1125.     def values(self):
  1126.         return self.dict.values()
  1127.     def items(self):
  1128.         return self.dict.items() 
  1129.     def __len__( self ):
  1130.         return len(self.dict)
  1131.  
  1132.  
  1133. class SvFormContentDict(FormContentDict):
  1134.     """Strict single-value expecting form content as dictionary.
  1135.  
  1136.     IF you only expect a single value for each field, then form[key]
  1137.     will return that single value.  It will raise an IndexError if
  1138.     that expectation is not true.  IF you expect a field to have
  1139.     possible multiple values, than you can use form.getlist(key) to
  1140.     get all of the values.  values() and items() are a compromise:
  1141.     they return single strings where there is a single value, and
  1142.     lists of strings otherwise.
  1143.  
  1144.     """
  1145.     def __getitem__(self, key):
  1146.         if len(self.dict[key]) > 1: 
  1147.             raise IndexError, 'expecting a single value' 
  1148.         return self.dict[key][0]
  1149.     def getlist(self, key):
  1150.         return self.dict[key]
  1151.     def values(self):
  1152.         lis = []
  1153.         for each in self.dict.values(): 
  1154.             if len( each ) == 1 : 
  1155.                 lis.append(each[0])
  1156.             else: lis.append(each)
  1157.         return lis
  1158.     def items(self):
  1159.         lis = []
  1160.         for key,value in self.dict.items():
  1161.             if len(value) == 1 :
  1162.                 lis.append((key, value[0]))
  1163.             else:       lis.append((key, value))
  1164.         return lis
  1165.  
  1166.  
  1167. class InterpFormContentDict(SvFormContentDict):
  1168.     """This class is present for backwards compatibility only.""" 
  1169.     def __getitem__( self, key ):
  1170.         v = SvFormContentDict.__getitem__( self, key )
  1171.         if v[0] in string.digits+'+-.' : 
  1172.             try:  return  string.atoi( v ) 
  1173.             except ValueError:
  1174.                 try:    return string.atof( v )
  1175.                 except ValueError: pass
  1176.         return string.strip(v)
  1177.     def values( self ):
  1178.         lis = [] 
  1179.         for key in self.keys():
  1180.             try:
  1181.                 lis.append( self[key] )
  1182.             except IndexError:
  1183.                 lis.append( self.dict[key] )
  1184.         return lis
  1185.     def items( self ):
  1186.         lis = [] 
  1187.         for key in self.keys():
  1188.             try:
  1189.                 lis.append( (key, self[key]) )
  1190.             except IndexError:
  1191.                 lis.append( (key, self.dict[key]) )
  1192.         return lis
  1193.  
  1194.  
  1195. class FormContent(FormContentDict):
  1196.     """This class is present for backwards compatibility only.""" 
  1197.     def values(self, key):
  1198.         if self.dict.has_key(key) :return self.dict[key]
  1199.         else: return None
  1200.     def indexed_value(self, key, location):
  1201.         if self.dict.has_key(key):
  1202.             if len (self.dict[key]) > location:
  1203.                 return self.dict[key][location]
  1204.             else: return None
  1205.         else: return None
  1206.     def value(self, key):
  1207.         if self.dict.has_key(key): return self.dict[key][0]
  1208.         else: return None
  1209.     def length(self, key):
  1210.         return len(self.dict[key])
  1211.     def stripped(self, key):
  1212.         if self.dict.has_key(key): return string.strip(self.dict[key][0])
  1213.         else: return None
  1214.     def pars(self):
  1215.         return self.dict
  1216.  
  1217.  
  1218. # Test/debug code
  1219. # ===============
  1220.  
  1221. def test(environ=os.environ):
  1222.     """Robust test CGI script, usable as main program.
  1223.  
  1224.     Write minimal HTTP headers and dump all information provided to
  1225.     the script in HTML form.
  1226.  
  1227.     """
  1228.     import traceback
  1229.     print "Content-type: text/html"
  1230.     print
  1231.     sys.stderr = sys.stdout
  1232.     try:
  1233.         form = FieldStorage()   # Replace with other classes to test those
  1234.         print_form(form)
  1235.         print_environ(environ)
  1236.         print_directory()
  1237.         print_arguments()
  1238.         print_environ_usage()
  1239.         def f():
  1240.             exec "testing print_exception() -- <I>italics?</I>"
  1241.         def g(f=f):
  1242.             f()
  1243.         print "<H3>What follows is a test, not an actual exception:</H3>"
  1244.         g()
  1245.     except:
  1246.         print_exception()
  1247.  
  1248.     # Second try with a small maxlen...
  1249.     global maxlen
  1250.     maxlen = 50
  1251.     try:
  1252.         form = FieldStorage()   # Replace with other classes to test those
  1253.         print_form(form)
  1254.         print_environ(environ)
  1255.         print_directory()
  1256.         print_arguments()
  1257.         print_environ_usage()
  1258.     except:
  1259.         print_exception()
  1260.  
  1261. def print_exception(type=None, value=None, tb=None, limit=None):
  1262.     if type is None:
  1263.         type, value, tb = sys.exc_info()
  1264.     import traceback
  1265.     print
  1266.     print "<H3>Traceback (innermost last):</H3>"
  1267.     list = traceback.format_tb(tb, limit) + \
  1268.            traceback.format_exception_only(type, value)
  1269.     print "<PRE>%s<B>%s</B></PRE>" % (
  1270.         escape(string.join(list[:-1], "")),
  1271.         escape(list[-1]),
  1272.         )
  1273.     del tb
  1274.  
  1275. def print_environ(environ=os.environ):
  1276.     """Dump the shell environment as HTML."""
  1277.     keys = environ.keys()
  1278.     keys.sort()
  1279.     print
  1280.     print "<H3>Shell Environment:</H3>"
  1281.     print "<DL>"
  1282.     for key in keys:
  1283.         print "<DT>", escape(key), "<DD>", escape(environ[key])
  1284.     print "</DL>" 
  1285.     print
  1286.  
  1287. def print_form(form):
  1288.     """Dump the contents of a form as HTML."""
  1289.     keys = form.keys()
  1290.     keys.sort()
  1291.     print
  1292.     print "<H3>Form Contents:</H3>"
  1293.     print "<DL>"
  1294.     for key in keys:
  1295.         print "<DT>" + escape(key) + ":",
  1296.         value = form[key]
  1297.         print "<i>" + escape(`type(value)`) + "</i>"
  1298.         print "<DD>" + escape(`value`)
  1299.     print "</DL>"
  1300.     print
  1301.  
  1302. def print_directory():
  1303.     """Dump the current directory as HTML."""
  1304.     print
  1305.     print "<H3>Current Working Directory:</H3>"
  1306.     try:
  1307.         pwd = os.getcwd()
  1308.     except os.error, msg:
  1309.         print "os.error:", escape(str(msg))
  1310.     else:
  1311.         print escape(pwd)
  1312.     print
  1313.  
  1314. def print_arguments():
  1315.     print
  1316.     print "<H3>Command Line Arguments:</H3>"
  1317.     print
  1318.     print sys.argv
  1319.     print
  1320.  
  1321. def print_environ_usage():
  1322.     """Dump a list of environment variables used by CGI as HTML."""
  1323.     print """
  1324. <H3>These environment variables could have been set:</H3>
  1325. <UL>
  1326. <LI>AUTH_TYPE
  1327. <LI>CONTENT_LENGTH
  1328. <LI>CONTENT_TYPE
  1329. <LI>DATE_GMT
  1330. <LI>DATE_LOCAL
  1331. <LI>DOCUMENT_NAME
  1332. <LI>DOCUMENT_ROOT
  1333. <LI>DOCUMENT_URI
  1334. <LI>GATEWAY_INTERFACE
  1335. <LI>LAST_MODIFIED
  1336. <LI>PATH
  1337. <LI>PATH_INFO
  1338. <LI>PATH_TRANSLATED
  1339. <LI>QUERY_STRING
  1340. <LI>REMOTE_ADDR
  1341. <LI>REMOTE_HOST
  1342. <LI>REMOTE_IDENT
  1343. <LI>REMOTE_USER
  1344. <LI>REQUEST_METHOD
  1345. <LI>SCRIPT_NAME
  1346. <LI>SERVER_NAME
  1347. <LI>SERVER_PORT
  1348. <LI>SERVER_PROTOCOL
  1349. <LI>SERVER_ROOT
  1350. <LI>SERVER_SOFTWARE
  1351. </UL>
  1352. In addition, HTTP headers sent by the server may be passed in the
  1353. environment as well.  Here are some common variable names:
  1354. <UL>
  1355. <LI>HTTP_ACCEPT
  1356. <LI>HTTP_CONNECTION
  1357. <LI>HTTP_HOST
  1358. <LI>HTTP_PRAGMA
  1359. <LI>HTTP_REFERER
  1360. <LI>HTTP_USER_AGENT
  1361. </UL>
  1362. """
  1363.  
  1364.  
  1365. # Utilities
  1366. # =========
  1367.  
  1368. def escape(s, quote=None):
  1369.     """Replace special characters '&', '<' and '>' by SGML entities."""
  1370.     s = string.replace(s, "&", "&") # Must be done first!
  1371.     s = string.replace(s, "<", "<")
  1372.     s = string.replace(s, ">", ">",)
  1373.     if quote:
  1374.         s = string.replace(s, '"', """)
  1375.     return s
  1376.  
  1377.  
  1378. # Invoke mainline
  1379. # ===============
  1380.  
  1381. # Call test() when this file is run as a script (not imported as a module)
  1382. if __name__ == '__main__': 
  1383.     test()
  1384.