home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.4 / cgi.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-04-29  |  31.6 KB  |  1,152 lines

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