home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / CGI.PY < prev    next >
Encoding:
Python Source  |  2000-10-03  |  32.3 KB  |  991 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. # XXX Perhaps there should be a slimmed version that doesn't contain
  10. # all those backwards compatible and debugging classes and functions?
  11.  
  12. # History
  13. # -------
  14. # Michael McLay started this module.  Steve Majewski changed the
  15. # interface to SvFormContentDict and FormContentDict.  The multipart
  16. # parsing was inspired by code submitted by Andreas Paepcke.  Guido van
  17. # Rossum rewrote, reformatted and documented the module and is currently
  18. # responsible for its maintenance.
  19.  
  20. __version__ = "2.4"
  21.  
  22.  
  23. # Imports
  24. # =======
  25.  
  26. import string
  27. import sys
  28. import os
  29. import urllib
  30. import mimetools
  31. import rfc822
  32. import UserDict
  33. from StringIO import StringIO
  34.  
  35.  
  36. # Logging support
  37. # ===============
  38.  
  39. logfile = ""            # Filename to log to, if not empty
  40. logfp = None            # File object to log to, if not None
  41.  
  42. def initlog(*allargs):
  43.     """Write a log message, if there is a log file.
  44.  
  45.     Even though this function is called initlog(), you should always
  46.     use log(); log is a variable that is set either to initlog
  47.     (initially), to dolog (once the log file has been opened), or to
  48.     nolog (when logging is disabled).
  49.  
  50.     The first argument is a format string; the remaining arguments (if
  51.     any) are arguments to the % operator, so e.g.
  52.         log("%s: %s", "a", "b")
  53.     will write "a: b" to the log file, followed by a newline.
  54.  
  55.     If the global logfp is not None, it should be a file object to
  56.     which log data is written.
  57.  
  58.     If the global logfp is None, the global logfile may be a string
  59.     giving a filename to open, in append mode.  This file should be
  60.     world writable!!!  If the file can't be opened, logging is
  61.     silently disabled (since there is no safe place where we could
  62.     send an error message).
  63.  
  64.     """
  65.     global logfp, log
  66.     if logfile and not logfp:
  67.         try:
  68.             logfp = open(logfile, "a")
  69.         except IOError:
  70.             pass
  71.     if not logfp:
  72.         log = nolog
  73.     else:
  74.         log = dolog
  75.     apply(log, allargs)
  76.  
  77. def dolog(fmt, *args):
  78.     """Write a log message to the log file.  See initlog() for docs."""
  79.     logfp.write(fmt%args + "\n")
  80.  
  81. def nolog(*allargs):
  82.     """Dummy function, assigned to log when logging is disabled."""
  83.     pass
  84.  
  85. log = initlog           # The current logging function
  86.  
  87.  
  88. # Parsing functions
  89. # =================
  90.  
  91. # Maximum input we will accept when REQUEST_METHOD is POST
  92. # 0 ==> unlimited input
  93. maxlen = 0
  94.  
  95. def parse(fp=None, environ=os.environ, keep_blank_values=0, strict_parsing=0):
  96.     """Parse a query in the environment or from a file (default stdin)
  97.  
  98.         Arguments, all optional:
  99.  
  100.         fp              : file pointer; default: sys.stdin
  101.  
  102.         environ         : environment dictionary; default: os.environ
  103.  
  104.         keep_blank_values: flag indicating whether blank values in
  105.             URL encoded forms should be treated as blank strings.  
  106.             A true value indicates that blanks should be retained as 
  107.             blank strings.  The default false value indicates that
  108.             blank values are to be ignored and treated as if they were
  109.             not included.
  110.  
  111.         strict_parsing: flag indicating what to do with parsing errors.
  112.             If false (the default), errors are silently ignored.
  113.             If true, errors raise a ValueError exception.
  114.     """
  115.     if not fp:
  116.         fp = sys.stdin
  117.     if not environ.has_key('REQUEST_METHOD'):
  118.         environ['REQUEST_METHOD'] = 'GET'       # For testing stand-alone
  119.     if environ['REQUEST_METHOD'] == 'POST':
  120.         ctype, pdict = parse_header(environ['CONTENT_TYPE'])
  121.         if ctype == 'multipart/form-data':
  122.             return parse_multipart(fp, pdict)
  123.         elif ctype == 'application/x-www-form-urlencoded':
  124.             clength = string.atoi(environ['CONTENT_LENGTH'])
  125.             if maxlen and clength > maxlen:
  126.                 raise ValueError, 'Maximum content length exceeded'
  127.             qs = fp.read(clength)
  128.         else:
  129.             qs = ''                     # Unknown content-type
  130.         if environ.has_key('QUERY_STRING'): 
  131.             if qs: qs = qs + '&'
  132.             qs = qs + environ['QUERY_STRING']
  133.         elif sys.argv[1:]: 
  134.             if qs: qs = qs + '&'
  135.             qs = qs + sys.argv[1]
  136.         environ['QUERY_STRING'] = qs    # XXX Shouldn't, really
  137.     elif environ.has_key('QUERY_STRING'):
  138.         qs = environ['QUERY_STRING']
  139.     else:
  140.         if sys.argv[1:]:
  141.             qs = sys.argv[1]
  142.         else:
  143.             qs = ""
  144.         environ['QUERY_STRING'] = qs    # XXX Shouldn't, really
  145.     return parse_qs(qs, keep_blank_values, strict_parsing)
  146.  
  147.  
  148. def parse_qs(qs, keep_blank_values=0, strict_parsing=0):
  149.     """Parse a query given as a string argument.
  150.  
  151.         Arguments:
  152.  
  153.         qs: URL-encoded query string to be parsed
  154.  
  155.         keep_blank_values: flag indicating whether blank values in
  156.             URL encoded queries should be treated as blank strings.  
  157.             A true value indicates that blanks should be retained as 
  158.             blank strings.  The default false value indicates that
  159.             blank values are to be ignored and treated as if they were
  160.             not included.
  161.  
  162.         strict_parsing: flag indicating what to do with parsing errors.
  163.             If false (the default), errors are silently ignored.
  164.             If true, errors raise a ValueError exception.
  165.     """
  166.     dict = {}
  167.     for name, value in parse_qsl(qs, keep_blank_values, strict_parsing):
  168.         if dict.has_key(name):
  169.             dict[name].append(value)
  170.         else:
  171.             dict[name] = [value]
  172.     return dict
  173.  
  174. def parse_qsl(qs, keep_blank_values=0, strict_parsing=0):
  175.     """Parse a query given as a string argument.
  176.  
  177.     Arguments:
  178.  
  179.     qs: URL-encoded query string to be parsed
  180.  
  181.     keep_blank_values: flag indicating whether blank values in
  182.         URL encoded queries should be treated as blank strings.  A
  183.         true value indicates that blanks should be retained as blank
  184.         strings.  The default false value indicates that blank values
  185.         are to be ignored and treated as if they were  not included.
  186.  
  187.     strict_parsing: flag indicating what to do with parsing errors. If
  188.         false (the default), errors are silently ignored. If true,
  189.         errors raise a ValueError exception. 
  190.  
  191.     Returns a list, as G-d intended.
  192.     """
  193.     pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
  194.     r = []
  195.     for name_value in pairs:
  196.         nv = name_value.split('=', 1)
  197.         if len(nv) != 2:
  198.             if strict_parsing:
  199.                 raise ValueError, "bad query field: %s" % `name_value`
  200.             continue
  201.         if len(nv[1]) or keep_blank_values:
  202.             name = urllib.unquote(string.replace(nv[0], '+', ' '))
  203.             value = urllib.unquote(string.replace(nv[1], '+', ' '))
  204.             r.append((name, value))
  205.  
  206.     return r
  207.  
  208.  
  209. def parse_multipart(fp, pdict):
  210.     """Parse multipart input.
  211.  
  212.     Arguments:
  213.     fp   : input file
  214.     pdict: dictionary containing other parameters of conten-type header
  215.  
  216.     Returns a dictionary just like parse_qs(): keys are the field names, each 
  217.     value is a list of values for that field.  This is easy to use but not 
  218.     much good if you are expecting megabytes to be uploaded -- in that case, 
  219.     use the FieldStorage class instead which is much more flexible.  Note 
  220.     that content-type is the raw, unparsed contents of the content-type 
  221.     header.
  222.     
  223.     XXX This does not parse nested multipart parts -- use FieldStorage for 
  224.     that.
  225.     
  226.     XXX This should really be subsumed by FieldStorage altogether -- no 
  227.     point in having two implementations of the same parsing algorithm.
  228.  
  229.     """
  230.     if pdict.has_key('boundary'):
  231.         boundary = pdict['boundary']
  232.     else:
  233.         boundary = ""
  234.     nextpart = "--" + boundary
  235.     lastpart = "--" + boundary + "--"
  236.     partdict = {}
  237.     terminator = ""
  238.  
  239.     while terminator != lastpart:
  240.         bytes = -1
  241.         data = None
  242.         if terminator:
  243.             # At start of next part.  Read headers first.
  244.             headers = mimetools.Message(fp)
  245.             clength = headers.getheader('content-length')
  246.             if clength:
  247.                 try:
  248.                     bytes = string.atoi(clength)
  249.                 except string.atoi_error:
  250.                     pass
  251.             if bytes > 0:
  252.                 if maxlen and bytes > maxlen:
  253.                     raise ValueError, 'Maximum content length exceeded'
  254.                 data = fp.read(bytes)
  255.             else:
  256.                 data = ""
  257.         # Read lines until end of part.
  258.         lines = []
  259.         while 1:
  260.             line = fp.readline()
  261.             if not line:
  262.                 terminator = lastpart # End outer loop
  263.                 break
  264.             if line[:2] == "--":
  265.                 terminator = string.strip(line)
  266.                 if terminator in (nextpart, lastpart):
  267.                     break
  268.             lines.append(line)
  269.         # Done with part.
  270.         if data is None:
  271.             continue
  272.         if bytes < 0:
  273.             if lines:
  274.                 # Strip final line terminator
  275.                 line = lines[-1]
  276.                 if line[-2:] == "\r\n":
  277.                     line = line[:-2]
  278.                 elif line[-1:] == "\n":
  279.                     line = line[:-1]
  280.                 lines[-1] = line
  281.                 data = string.joinfields(lines, "")
  282.         line = headers['content-disposition']
  283.         if not line:
  284.             continue
  285.         key, params = parse_header(line)
  286.         if key != 'form-data':
  287.             continue
  288.         if params.has_key('name'):
  289.             name = params['name']
  290.         else:
  291.             continue
  292.         if partdict.has_key(name):
  293.             partdict[name].append(data)
  294.         else:
  295.             partdict[name] = [data]
  296.  
  297.     return partdict
  298.  
  299.  
  300. def parse_header(line):
  301.     """Parse a Content-type like header.
  302.  
  303.     Return the main content-type and a dictionary of options.
  304.  
  305.     """
  306.     plist = map(string.strip, string.splitfields(line, ';'))
  307.     key = string.lower(plist[0])
  308.     del plist[0]
  309.     pdict = {}
  310.     for p in plist:
  311.         i = string.find(p, '=')
  312.         if i >= 0:
  313.             name = string.lower(string.strip(p[:i]))
  314.             value = string.strip(p[i+1:])
  315.             if len(value) >= 2 and value[0] == value[-1] == '"':
  316.                 value = value[1:-1]
  317.             pdict[name] = value
  318.     return key, pdict
  319.  
  320.  
  321. # Classes for field storage
  322. # =========================
  323.  
  324. class MiniFieldStorage:
  325.  
  326.     """Like FieldStorage, for use when no file uploads are possible."""
  327.  
  328.     # Dummy attributes
  329.     filename = None
  330.     list = None
  331.     type = None
  332.     file = None
  333.     type_options = {}
  334.     disposition = None
  335.     disposition_options = {}
  336.     headers = {}
  337.  
  338.     def __init__(self, name, value):
  339.         """Constructor from field name and value."""
  340.         self.name = name
  341.         self.value = value
  342.         # self.file = StringIO(value)
  343.  
  344.     def __repr__(self):
  345.         """Return printable representation."""
  346.         return "MiniFieldStorage(%s, %s)" % (`self.name`, `self.value`)
  347.  
  348.  
  349. class FieldStorage:
  350.  
  351.     """Store a sequence of fields, reading multipart/form-data.
  352.  
  353.     This class provides naming, typing, files stored on disk, and
  354.     more.  At the top level, it is accessible like a dictionary, whose
  355.     keys are the field names.  (Note: None can occur as a field name.)
  356.     The items are either a Python list (if there's multiple values) or
  357.     another FieldStorage or MiniFieldStorage object.  If it's a single
  358.     object, it has the following attributes:
  359.  
  360.     name: the field name, if specified; otherwise None
  361.  
  362.     filename: the filename, if specified; otherwise None; this is the
  363.         client side filename, *not* the file name on which it is
  364.         stored (that's a temporary file you don't deal with)
  365.  
  366.     value: the value as a *string*; for file uploads, this
  367.         transparently reads the file every time you request the value
  368.  
  369.     file: the file(-like) object from which you can read the data;
  370.         None if the data is stored a simple string
  371.  
  372.     type: the content-type, or None if not specified
  373.  
  374.     type_options: dictionary of options specified on the content-type
  375.         line
  376.  
  377.     disposition: content-disposition, or None if not specified
  378.  
  379.     disposition_options: dictionary of corresponding options
  380.  
  381.     headers: a dictionary(-like) object (sometimes rfc822.Message or a
  382.         subclass thereof) containing *all* headers
  383.  
  384.     The class is subclassable, mostly for the purpose of overriding
  385.     the make_file() method, which is called internally to come up with
  386.     a file open for reading and writing.  This makes it possible to
  387.     override the default choice of storing all files in a temporary
  388.     directory and unlinking them as soon as they have been opened.
  389.  
  390.     """
  391.  
  392.     def __init__(self, fp=None, headers=None, outerboundary="",
  393.                  environ=os.environ, keep_blank_values=0, strict_parsing=0):
  394.         """Constructor.  Read multipart/* until last part.
  395.  
  396.         Arguments, all optional:
  397.  
  398.         fp              : file pointer; default: sys.stdin
  399.             (not used when the request method is GET)
  400.  
  401.         headers         : header dictionary-like object; default:
  402.             taken from environ as per CGI spec
  403.  
  404.         outerboundary   : terminating multipart boundary
  405.             (for internal use only)
  406.  
  407.         environ         : environment dictionary; default: os.environ
  408.  
  409.         keep_blank_values: flag indicating whether blank values in
  410.             URL encoded forms should be treated as blank strings.  
  411.             A true value indicates that blanks should be retained as 
  412.             blank strings.  The default false value indicates that
  413.             blank values are to be ignored and treated as if they were
  414.             not included.
  415.  
  416.         strict_parsing: flag indicating what to do with parsing errors.
  417.             If false (the default), errors are silently ignored.
  418.             If true, errors raise a ValueError exception.
  419.  
  420.         """
  421.         method = 'GET'
  422.         self.keep_blank_values = keep_blank_values
  423.         self.strict_parsing = strict_parsing
  424.         if environ.has_key('REQUEST_METHOD'):
  425.             method = string.upper(environ['REQUEST_METHOD'])
  426.         if method == 'GET' or method == 'HEAD':
  427.             if environ.has_key('QUERY_STRING'):
  428.                 qs = environ['QUERY_STRING']
  429.             elif sys.argv[1:]:
  430.                 qs = sys.argv[1]
  431.             else:
  432.                 qs = ""
  433.             fp = StringIO(qs)
  434.             if headers is None:
  435.                 headers = {'content-type':
  436.                            "application/x-www-form-urlencoded"}
  437.         if headers is None:
  438.             headers = {}
  439.             if method == 'POST':
  440.                 # Set default content-type for POST to what's traditional
  441.                 headers['content-type'] = "application/x-www-form-urlencoded"
  442.             if environ.has_key('CONTENT_TYPE'):
  443.                 headers['content-type'] = environ['CONTENT_TYPE']
  444.             if environ.has_key('CONTENT_LENGTH'):
  445.                 headers['content-length'] = environ['CONTENT_LENGTH']
  446.         self.fp = fp or sys.stdin
  447.         self.headers = headers
  448.         self.outerboundary = outerboundary
  449.  
  450.         # Process content-disposition header
  451.         cdisp, pdict = "", {}
  452.         if self.headers.has_key('content-disposition'):
  453.             cdisp, pdict = parse_header(self.headers['content-disposition'])
  454.         self.disposition = cdisp
  455.         self.disposition_options = pdict
  456.         self.name = None
  457.         if pdict.has_key('name'):
  458.             self.name = pdict['name']
  459.         self.filename = None
  460.         if pdict.has_key('filename'):
  461.             self.filename = pdict['filename']
  462.  
  463.         # Process content-type header
  464.         #
  465.         # Honor any existing content-type header.  But if there is no
  466.         # content-type header, use some sensible defaults.  Assume
  467.         # outerboundary is "" at the outer level, but something non-false
  468.         # inside a multi-part.  The default for an inner part is text/plain,
  469.         # but for an outer part it should be urlencoded.  This should catch
  470.         # bogus clients which erroneously forget to include a content-type
  471.         # header.
  472.         #
  473.         # See below for what we do if there does exist a content-type header,
  474.         # but it happens to be something we don't understand.
  475.         if self.headers.has_key('content-type'):
  476.             ctype, pdict = parse_header(self.headers['content-type'])
  477.         elif self.outerboundary or method != 'POST':
  478.             ctype, pdict = "text/plain", {}
  479.         else:
  480.             ctype, pdict = 'application/x-www-form-urlencoded', {}
  481.         self.type = ctype
  482.         self.type_options = pdict
  483.         self.innerboundary = ""
  484.         if pdict.has_key('boundary'):
  485.             self.innerboundary = pdict['boundary']
  486.         clen = -1
  487.         if self.headers.has_key('content-length'):
  488.             try:
  489.                 clen = string.atoi(self.headers['content-length'])
  490.             except:
  491.                 pass
  492.             if maxlen and clen > maxlen:
  493.                 raise ValueError, 'Maximum content length exceeded'
  494.         self.length = clen
  495.  
  496.         self.list = self.file = None
  497.         self.done = 0
  498.         self.lines = []
  499.         if ctype == 'application/x-www-form-urlencoded':
  500.             self.read_urlencoded()
  501.         elif ctype[:10] == 'multipart/':
  502.             self.read_multi(environ, keep_blank_values, strict_parsing)
  503.         else:
  504.             self.read_single()
  505.  
  506.     def __repr__(self):
  507.         """Return a printable representation."""
  508.         return "FieldStorage(%s, %s, %s)" % (
  509.                 `self.name`, `self.filename`, `self.value`)
  510.  
  511.     def __getattr__(self, name):
  512.         if name != 'value':
  513.             raise AttributeError, name
  514.         if self.file:
  515.             self.file.seek(0)
  516.             value = self.file.read()
  517.             self.file.seek(0)
  518.         elif self.list is not None:
  519.             value = self.list
  520.         else:
  521.             value = None
  522.         return value
  523.  
  524.     def __getitem__(self, key):
  525.         """Dictionary style indexing."""
  526.         if self.list is None:
  527.             raise TypeError, "not indexable"
  528.         found = []
  529.         for item in self.list:
  530.             if item.name == key: found.append(item)
  531.         if not found:
  532.             raise KeyError, key
  533.         if len(found) == 1:
  534.             return found[0]
  535.         else:
  536.             return found
  537.  
  538.     def getvalue(self, key, default=None):
  539.         """Dictionary style get() method, including 'value' lookup."""
  540.         if self.has_key(key):
  541.             value = self[key]
  542.             if type(value) is type([]):
  543.                 return map(lambda v: v.value, value)
  544.             else:
  545.                 return value.value
  546.         else:
  547.             return default
  548.  
  549.     def keys(self):
  550.         """Dictionary style keys() method."""
  551.         if self.list is None:
  552.             raise TypeError, "not indexable"
  553.         keys = []
  554.         for item in self.list:
  555.             if item.name not in keys: keys.append(item.name)
  556.         return keys
  557.  
  558.     def has_key(self, key):
  559.         """Dictionary style has_key() method."""
  560.         if self.list is None:
  561.             raise TypeError, "not indexable"
  562.         for item in self.list:
  563.             if item.name == key: return 1
  564.         return 0
  565.  
  566.     def __len__(self):
  567.         """Dictionary style len(x) support."""
  568.         return len(self.keys())
  569.  
  570.     def read_urlencoded(self):
  571.         """Internal: read data in query string format."""
  572.         qs = self.fp.read(self.length)
  573.         self.list = list = []
  574.         for key, value in parse_qsl(qs, self.keep_blank_values,
  575.                                     self.strict_parsing):
  576.             list.append(MiniFieldStorage(key, value))
  577.         self.skip_lines()
  578.  
  579.     FieldStorageClass = None
  580.  
  581.     def read_multi(self, environ, keep_blank_values, strict_parsing):
  582.         """Internal: read a part that is itself multipart."""
  583.         self.list = []
  584.         klass = self.FieldStorageClass or self.__class__
  585.         part = klass(self.fp, {}, self.innerboundary,
  586.                      environ, keep_blank_values, strict_parsing)
  587.         # Throw first part away
  588.         while not part.done:
  589.             headers = rfc822.Message(self.fp)
  590.             part = klass(self.fp, headers, self.innerboundary,
  591.                          environ, keep_blank_values, strict_parsing)
  592.             self.list.append(part)
  593.         self.skip_lines()
  594.  
  595.     def read_single(self):
  596.         """Internal: read an atomic part."""
  597.         if self.length >= 0:
  598.             self.read_binary()
  599.             self.skip_lines()
  600.         else:
  601.             self.read_lines()
  602.         self.file.seek(0)
  603.  
  604.     bufsize = 8*1024            # I/O buffering size for copy to file
  605.  
  606.     def read_binary(self):
  607.         """Internal: read binary data."""
  608.         self.file = self.make_file('b')
  609.         todo = self.length
  610.         if todo >= 0:
  611.             while todo > 0:
  612.                 data = self.fp.read(min(todo, self.bufsize))
  613.                 if not data:
  614.                     self.done = -1
  615.                     break
  616.                 self.file.write(data)
  617.                 todo = todo - len(data)
  618.  
  619.     def read_lines(self):
  620.         """Internal: read lines until EOF or outerboundary."""
  621.         self.file = self.make_file('')
  622.         if self.outerboundary:
  623.             self.read_lines_to_outerboundary()
  624.         else:
  625.             self.read_lines_to_eof()
  626.  
  627.     def read_lines_to_eof(self):
  628.         """Internal: read lines until EOF."""
  629.         while 1:
  630.             line = self.fp.readline()
  631.             if not line:
  632.                 self.done = -1
  633.                 break
  634.             self.lines.append(line)
  635.             self.file.write(line)
  636.  
  637.     def read_lines_to_outerboundary(self):
  638.         """Internal: read lines until outerboundary."""
  639.         next = "--" + self.outerboundary
  640.         last = next + "--"
  641.         delim = ""
  642.         while 1:
  643.             line = self.fp.readline()
  644.             if not line:
  645.                 self.done = -1
  646.                 break
  647.             self.lines.append(line)
  648.             if line[:2] == "--":
  649.                 strippedline = string.strip(line)
  650.                 if strippedline == next:
  651.                     break
  652.                 if strippedline == last:
  653.                     self.done = 1
  654.                     break
  655.             odelim = delim
  656.             if line[-2:] == "\r\n":
  657.                 delim = "\r\n"
  658.                 line = line[:-2]
  659.             elif line[-1] == "\n":
  660.                 delim = "\n"
  661.                 line = line[:-1]
  662.             else:
  663.                 delim = ""
  664.             self.file.write(odelim + line)
  665.  
  666.     def skip_lines(self):
  667.         """Internal: skip lines until outer boundary if defined."""
  668.         if not self.outerboundary or self.done:
  669.             return
  670.         next = "--" + self.outerboundary
  671.         last = next + "--"
  672.         while 1:
  673.             line = self.fp.readline()
  674.             if not line:
  675.                 self.done = -1
  676.                 break
  677.             self.lines.append(line)
  678.             if line[:2] == "--":
  679.                 strippedline = string.strip(line)
  680.                 if strippedline == next:
  681.                     break
  682.                 if strippedline == last:
  683.                     self.done = 1
  684.                     break
  685.  
  686.     def make_file(self, binary=None):
  687.         """Overridable: return a readable & writable file.
  688.  
  689.         The file will be used as follows:
  690.         - data is written to it
  691.         - seek(0)
  692.         - data is read from it
  693.  
  694.         The 'binary' argument is unused -- the file is always opened
  695.         in binary mode.
  696.  
  697.         This version opens a temporary file for reading and writing,
  698.         and immediately deletes (unlinks) it.  The trick (on Unix!) is
  699.         that the file can still be used, but it can't be opened by
  700.         another process, and it will automatically be deleted when it
  701.         is closed or when the current process terminates.
  702.  
  703.         If you want a more permanent file, you derive a class which
  704.         overrides this method.  If you want a visible temporary file
  705.         that is nevertheless automatically deleted when the script
  706.         terminates, try defining a __del__ method in a derived class
  707.         which unlinks the temporary files you have created.
  708.  
  709.         """
  710.         import tempfile
  711.         return tempfile.TemporaryFile("w+b")
  712.         
  713.  
  714.  
  715. # Backwards Compatibility Classes
  716. # ===============================
  717.  
  718. class FormContentDict(UserDict.UserDict):
  719.     """Form content as dictionary with a list of values per field.
  720.  
  721.     form = FormContentDict()
  722.  
  723.     form[key] -> [value, value, ...]
  724.     form.has_key(key) -> Boolean
  725.     form.keys() -> [key, key, ...]
  726.     form.values() -> [[val, val, ...], [val, val, ...], ...]
  727.     form.items() ->  [(key, [val, val, ...]), (key, [val, val, ...]), ...]
  728.     form.dict == {key: [val, val, ...], ...}
  729.  
  730.     """
  731.     def __init__(self, environ=os.environ):
  732.         self.dict = self.data = parse(environ=environ)
  733.         self.query_string = environ['QUERY_STRING']
  734.  
  735.  
  736. class SvFormContentDict(FormContentDict):
  737.     """Form content as dictionary expecting a single value per field.
  738.  
  739.     If you only expect a single value for each field, then form[key]
  740.     will return that single value.  It will raise an IndexError if
  741.     that expectation is not true.  If you expect a field to have
  742.     possible multiple values, than you can use form.getlist(key) to
  743.     get all of the values.  values() and items() are a compromise:
  744.     they return single strings where there is a single value, and
  745.     lists of strings otherwise.
  746.  
  747.     """
  748.     def __getitem__(self, key):
  749.         if len(self.dict[key]) > 1: 
  750.             raise IndexError, 'expecting a single value' 
  751.         return self.dict[key][0]
  752.     def getlist(self, key):
  753.         return self.dict[key]
  754.     def values(self):
  755.         result = []
  756.         for value in self.dict.values():
  757.             if len(value) == 1:
  758.                 result.append(value[0])
  759.             else: result.append(value)
  760.         return result
  761.     def items(self):
  762.         result = []
  763.         for key, value in self.dict.items():
  764.             if len(value) == 1:
  765.                 result.append((key, value[0]))
  766.             else: result.append((key, value))
  767.         return result
  768.  
  769.  
  770. class InterpFormContentDict(SvFormContentDict):
  771.     """This class is present for backwards compatibility only.""" 
  772.     def __getitem__(self, key):
  773.         v = SvFormContentDict.__getitem__(self, key)
  774.         if v[0] in string.digits + '+-.':
  775.             try: return string.atoi(v)
  776.             except ValueError:
  777.                 try: return string.atof(v)
  778.                 except ValueError: pass
  779.         return string.strip(v)
  780.     def values(self):
  781.         result = []
  782.         for key in self.keys():
  783.             try:
  784.                 result.append(self[key])
  785.             except IndexError:
  786.                 result.append(self.dict[key])
  787.         return result
  788.     def items(self):
  789.         result = []
  790.         for key in self.keys():
  791.             try:
  792.                 result.append((key, self[key]))
  793.             except IndexError:
  794.                 result.append((key, self.dict[key]))
  795.         return result
  796.  
  797.  
  798. class FormContent(FormContentDict):
  799.     """This class is present for backwards compatibility only.""" 
  800.     def values(self, key):
  801.         if self.dict.has_key(key) :return self.dict[key]
  802.         else: return None
  803.     def indexed_value(self, key, location):
  804.         if self.dict.has_key(key):
  805.             if len(self.dict[key]) > location:
  806.                 return self.dict[key][location]
  807.             else: return None
  808.         else: return None
  809.     def value(self, key):
  810.         if self.dict.has_key(key): return self.dict[key][0]
  811.         else: return None
  812.     def length(self, key):
  813.         return len(self.dict[key])
  814.     def stripped(self, key):
  815.         if self.dict.has_key(key): return string.strip(self.dict[key][0])
  816.         else: return None
  817.     def pars(self):
  818.         return self.dict
  819.  
  820.  
  821. # Test/debug code
  822. # ===============
  823.  
  824. def test(environ=os.environ):
  825.     """Robust test CGI script, usable as main program.
  826.  
  827.     Write minimal HTTP headers and dump all information provided to
  828.     the script in HTML form.
  829.  
  830.     """
  831.     import traceback
  832.     print "Content-type: text/html"
  833.     print
  834.     sys.stderr = sys.stdout
  835.     try:
  836.         form = FieldStorage()   # Replace with other classes to test those
  837.         print_directory()
  838.         print_arguments()
  839.         print_form(form)
  840.         print_environ(environ)
  841.         print_environ_usage()
  842.         def f():
  843.             exec "testing print_exception() -- <I>italics?</I>"
  844.         def g(f=f):
  845.             f()
  846.         print "<H3>What follows is a test, not an actual exception:</H3>"
  847.         g()
  848.     except:
  849.         print_exception()
  850.  
  851.     print "<H1>Second try with a small maxlen...</H1>"
  852.  
  853.     global maxlen
  854.     maxlen = 50
  855.     try:
  856.         form = FieldStorage()   # Replace with other classes to test those
  857.         print_directory()
  858.         print_arguments()
  859.         print_form(form)
  860.         print_environ(environ)
  861.     except:
  862.         print_exception()
  863.  
  864. def print_exception(type=None, value=None, tb=None, limit=None):
  865.     if type is None:
  866.         type, value, tb = sys.exc_info()
  867.     import traceback
  868.     print
  869.     print "<H3>Traceback (innermost last):</H3>"
  870.     list = traceback.format_tb(tb, limit) + \
  871.            traceback.format_exception_only(type, value)
  872.     print "<PRE>%s<B>%s</B></PRE>" % (
  873.         escape(string.join(list[:-1], "")),
  874.         escape(list[-1]),
  875.         )
  876.     del tb
  877.  
  878. def print_environ(environ=os.environ):
  879.     """Dump the shell environment as HTML."""
  880.     keys = environ.keys()
  881.     keys.sort()
  882.     print
  883.     print "<H3>Shell Environment:</H3>"
  884.     print "<DL>"
  885.     for key in keys:
  886.         print "<DT>", escape(key), "<DD>", escape(environ[key])
  887.     print "</DL>" 
  888.     print
  889.  
  890. def print_form(form):
  891.     """Dump the contents of a form as HTML."""
  892.     keys = form.keys()
  893.     keys.sort()
  894.     print
  895.     print "<H3>Form Contents:</H3>"
  896.     if not keys:
  897.         print "<P>No form fields."
  898.     print "<DL>"
  899.     for key in keys:
  900.         print "<DT>" + escape(key) + ":",
  901.         value = form[key]
  902.         print "<i>" + escape(`type(value)`) + "</i>"
  903.         print "<DD>" + escape(`value`)
  904.     print "</DL>"
  905.     print
  906.  
  907. def print_directory():
  908.     """Dump the current directory as HTML."""
  909.     print
  910.     print "<H3>Current Working Directory:</H3>"
  911.     try:
  912.         pwd = os.getcwd()
  913.     except os.error, msg:
  914.         print "os.error:", escape(str(msg))
  915.     else:
  916.         print escape(pwd)
  917.     print
  918.  
  919. def print_arguments():
  920.     print
  921.     print "<H3>Command Line Arguments:</H3>"
  922.     print
  923.     print sys.argv
  924.     print
  925.  
  926. def print_environ_usage():
  927.     """Dump a list of environment variables used by CGI as HTML."""
  928.     print """
  929. <H3>These environment variables could have been set:</H3>
  930. <UL>
  931. <LI>AUTH_TYPE
  932. <LI>CONTENT_LENGTH
  933. <LI>CONTENT_TYPE
  934. <LI>DATE_GMT
  935. <LI>DATE_LOCAL
  936. <LI>DOCUMENT_NAME
  937. <LI>DOCUMENT_ROOT
  938. <LI>DOCUMENT_URI
  939. <LI>GATEWAY_INTERFACE
  940. <LI>LAST_MODIFIED
  941. <LI>PATH
  942. <LI>PATH_INFO
  943. <LI>PATH_TRANSLATED
  944. <LI>QUERY_STRING
  945. <LI>REMOTE_ADDR
  946. <LI>REMOTE_HOST
  947. <LI>REMOTE_IDENT
  948. <LI>REMOTE_USER
  949. <LI>REQUEST_METHOD
  950. <LI>SCRIPT_NAME
  951. <LI>SERVER_NAME
  952. <LI>SERVER_PORT
  953. <LI>SERVER_PROTOCOL
  954. <LI>SERVER_ROOT
  955. <LI>SERVER_SOFTWARE
  956. </UL>
  957. In addition, HTTP headers sent by the server may be passed in the
  958. environment as well.  Here are some common variable names:
  959. <UL>
  960. <LI>HTTP_ACCEPT
  961. <LI>HTTP_CONNECTION
  962. <LI>HTTP_HOST
  963. <LI>HTTP_PRAGMA
  964. <LI>HTTP_REFERER
  965. <LI>HTTP_USER_AGENT
  966. </UL>
  967. """
  968.  
  969.  
  970. # Utilities
  971. # =========
  972.  
  973. def escape(s, quote=None):
  974.     """Replace special characters '&', '<' and '>' by SGML entities."""
  975.     s = string.replace(s, "&", "&") # Must be done first!
  976.     s = string.replace(s, "<", "<")
  977.     s = string.replace(s, ">", ">",)
  978.     if quote:
  979.         s = string.replace(s, '"', """)
  980.     return s
  981.  
  982.  
  983. # Invoke mainline
  984. # ===============
  985.  
  986. # Call test() when this file is run as a script (not imported as a module)
  987. if __name__ == '__main__': 
  988.     test()
  989.