Back to index

python3.2  3.2.2
Classes | Functions | Variables
cgi Namespace Reference

Classes

class  MiniFieldStorage
class  FieldStorage

Functions

def initlog
def dolog
def nolog
def parse
def parse_qs
def parse_qsl
def parse_multipart
def _parseparam
def parse_header
def test
def print_exception
def print_environ
def print_form
def print_directory
def print_arguments
def print_environ_usage
def escape
def valid_boundary

Variables

string __version__ = "2.6"
list __all__
string logfile = ""
 logfp = None
 log = initlog
int maxlen = 0

Function Documentation

def cgi._parseparam (   s) [private]

Definition at line 290 of file cgi.py.

00290 
00291 def _parseparam(s):
00292     while s[:1] == ';':
00293         s = s[1:]
00294         end = s.find(';')
00295         while end > 0 and s.count('"', 0, end) % 2:
00296             end = s.find(';', end + 1)
00297         if end < 0:
00298             end = len(s)
00299         f = s[:end]
00300         yield f.strip()
00301         s = s[end:]

Here is the caller graph for this function:

def cgi.dolog (   fmt,
  args 
)
Write a log message to the log file.  See initlog() for docs.

Definition at line 91 of file cgi.py.

00091 
00092 def dolog(fmt, *args):
00093     """Write a log message to the log file.  See initlog() for docs."""
00094     logfp.write(fmt%args + "\n")

def cgi.escape (   s,
  quote = None 
)
Deprecated API.

Definition at line 1003 of file cgi.py.

01003 
01004 def escape(s, quote=None):
01005     """Deprecated API."""
01006     warn("cgi.escape is deprecated, use html.escape instead",
01007          PendingDeprecationWarning, stacklevel=2)
01008     s = s.replace("&", "&amp;") # Must be done first!
01009     s = s.replace("<", "&lt;")
01010     s = s.replace(">", "&gt;")
01011     if quote:
01012         s = s.replace('"', "&quot;")
01013     return s
01014 

Here is the caller graph for this function:

def cgi.initlog (   allargs)
Write a log message, if there is a log file.

Even though this function is called initlog(), you should always
use log(); log is a variable that is set either to initlog
(initially), to dolog (once the log file has been opened), or to
nolog (when logging is disabled).

The first argument is a format string; the remaining arguments (if
any) are arguments to the % operator, so e.g.
    log("%s: %s", "a", "b")
will write "a: b" to the log file, followed by a newline.

If the global logfp is not None, it should be a file object to
which log data is written.

If the global logfp is None, the global logfile may be a string
giving a filename to open, in append mode.  This file should be
world writable!!!  If the file can't be opened, logging is
silently disabled (since there is no safe place where we could
send an error message).

Definition at line 56 of file cgi.py.

00056 
00057 def initlog(*allargs):
00058     """Write a log message, if there is a log file.
00059 
00060     Even though this function is called initlog(), you should always
00061     use log(); log is a variable that is set either to initlog
00062     (initially), to dolog (once the log file has been opened), or to
00063     nolog (when logging is disabled).
00064 
00065     The first argument is a format string; the remaining arguments (if
00066     any) are arguments to the % operator, so e.g.
00067         log("%s: %s", "a", "b")
00068     will write "a: b" to the log file, followed by a newline.
00069 
00070     If the global logfp is not None, it should be a file object to
00071     which log data is written.
00072 
00073     If the global logfp is None, the global logfile may be a string
00074     giving a filename to open, in append mode.  This file should be
00075     world writable!!!  If the file can't be opened, logging is
00076     silently disabled (since there is no safe place where we could
00077     send an error message).
00078 
00079     """
00080     global logfp, log
00081     if logfile and not logfp:
00082         try:
00083             logfp = open(logfile, "a")
00084         except IOError:
00085             pass
00086     if not logfp:
00087         log = nolog
00088     else:
00089         log = dolog
00090     log(*allargs)

Here is the caller graph for this function:

def cgi.nolog (   allargs)
Dummy function, assigned to log when logging is disabled.

Definition at line 95 of file cgi.py.

00095 
00096 def nolog(*allargs):
00097     """Dummy function, assigned to log when logging is disabled."""
00098     pass

def cgi.parse (   fp = None,
  environ = os.environ,
  keep_blank_values = 0,
  strict_parsing = 0 
)
Parse a query in the environment or from a file (default stdin)

    Arguments, all optional:

    fp              : file pointer; default: sys.stdin.buffer

    environ         : environment dictionary; default: os.environ

    keep_blank_values: flag indicating whether blank values in
        percent-encoded forms should be treated as blank strings.
        A true value indicates that blanks should be retained as
        blank strings.  The default false value indicates that
        blank values are to be ignored and treated as if they were
        not included.

    strict_parsing: flag indicating what to do with parsing errors.
        If false (the default), errors are silently ignored.
        If true, errors raise a ValueError exception.

Definition at line 109 of file cgi.py.

00109 
00110 def parse(fp=None, environ=os.environ, keep_blank_values=0, strict_parsing=0):
00111     """Parse a query in the environment or from a file (default stdin)
00112 
00113         Arguments, all optional:
00114 
00115         fp              : file pointer; default: sys.stdin.buffer
00116 
00117         environ         : environment dictionary; default: os.environ
00118 
00119         keep_blank_values: flag indicating whether blank values in
00120             percent-encoded forms should be treated as blank strings.
00121             A true value indicates that blanks should be retained as
00122             blank strings.  The default false value indicates that
00123             blank values are to be ignored and treated as if they were
00124             not included.
00125 
00126         strict_parsing: flag indicating what to do with parsing errors.
00127             If false (the default), errors are silently ignored.
00128             If true, errors raise a ValueError exception.
00129     """
00130     if fp is None:
00131         fp = sys.stdin
00132 
00133     # field keys and values (except for files) are returned as strings
00134     # an encoding is required to decode the bytes read from self.fp
00135     if hasattr(fp,'encoding'):
00136         encoding = fp.encoding
00137     else:
00138         encoding = 'latin-1'
00139 
00140     # fp.read() must return bytes
00141     if isinstance(fp, TextIOWrapper):
00142         fp = fp.buffer
00143 
00144     if not 'REQUEST_METHOD' in environ:
00145         environ['REQUEST_METHOD'] = 'GET'       # For testing stand-alone
00146     if environ['REQUEST_METHOD'] == 'POST':
00147         ctype, pdict = parse_header(environ['CONTENT_TYPE'])
00148         if ctype == 'multipart/form-data':
00149             return parse_multipart(fp, pdict)
00150         elif ctype == 'application/x-www-form-urlencoded':
00151             clength = int(environ['CONTENT_LENGTH'])
00152             if maxlen and clength > maxlen:
00153                 raise ValueError('Maximum content length exceeded')
00154             qs = fp.read(clength).decode(encoding)
00155         else:
00156             qs = ''                     # Unknown content-type
00157         if 'QUERY_STRING' in environ:
00158             if qs: qs = qs + '&'
00159             qs = qs + environ['QUERY_STRING']
00160         elif sys.argv[1:]:
00161             if qs: qs = qs + '&'
00162             qs = qs + sys.argv[1]
00163         environ['QUERY_STRING'] = qs    # XXX Shouldn't, really
00164     elif 'QUERY_STRING' in environ:
00165         qs = environ['QUERY_STRING']
00166     else:
00167         if sys.argv[1:]:
00168             qs = sys.argv[1]
00169         else:
00170             qs = ""
00171         environ['QUERY_STRING'] = qs    # XXX Shouldn't, really
00172     return urllib.parse.parse_qs(qs, keep_blank_values, strict_parsing,
00173                                  encoding=encoding)
00174 
00175 
00176 # parse query string function called from urlparse,
00177 # this is done in order to maintain backward compatiblity.

Here is the call graph for this function:

Here is the caller graph for this function:

def cgi.parse_header (   line)
Parse a Content-type like header.

Return the main content-type and a dictionary of options.

Definition at line 302 of file cgi.py.

00302 
00303 def parse_header(line):
00304     """Parse a Content-type like header.
00305 
00306     Return the main content-type and a dictionary of options.
00307 
00308     """
00309     parts = _parseparam(';' + line)
00310     key = parts.__next__()
00311     pdict = {}
00312     for p in parts:
00313         i = p.find('=')
00314         if i >= 0:
00315             name = p[:i].strip().lower()
00316             value = p[i+1:].strip()
00317             if len(value) >= 2 and value[0] == value[-1] == '"':
00318                 value = value[1:-1]
00319                 value = value.replace('\\\\', '\\').replace('\\"', '"')
00320             pdict[name] = value
00321     return key, pdict
00322 
00323 
00324 # Classes for field storage
00325 # =========================

Here is the call graph for this function:

Here is the caller graph for this function:

def cgi.parse_multipart (   fp,
  pdict 
)
Parse multipart input.

Arguments:
fp   : input file
pdict: dictionary containing other parameters of content-type header

Returns a dictionary just like parse_qs(): keys are the field names, each
value is a list of values for that field.  This is easy to use but not
much good if you are expecting megabytes to be uploaded -- in that case,
use the FieldStorage class instead which is much more flexible.  Note
that content-type is the raw, unparsed contents of the content-type
header.

XXX This does not parse nested multipart parts -- use FieldStorage for
that.

XXX This should really be subsumed by FieldStorage altogether -- no
point in having two implementations of the same parsing algorithm.
Also, FieldStorage protects itself better against certain DoS attacks
by limiting the size of the data read in one chunk.  The API here
does not support that kind of protection.  This also affects parse()
since it can call parse_multipart().

Definition at line 190 of file cgi.py.

00190 
00191 def parse_multipart(fp, pdict):
00192     """Parse multipart input.
00193 
00194     Arguments:
00195     fp   : input file
00196     pdict: dictionary containing other parameters of content-type header
00197 
00198     Returns a dictionary just like parse_qs(): keys are the field names, each
00199     value is a list of values for that field.  This is easy to use but not
00200     much good if you are expecting megabytes to be uploaded -- in that case,
00201     use the FieldStorage class instead which is much more flexible.  Note
00202     that content-type is the raw, unparsed contents of the content-type
00203     header.
00204 
00205     XXX This does not parse nested multipart parts -- use FieldStorage for
00206     that.
00207 
00208     XXX This should really be subsumed by FieldStorage altogether -- no
00209     point in having two implementations of the same parsing algorithm.
00210     Also, FieldStorage protects itself better against certain DoS attacks
00211     by limiting the size of the data read in one chunk.  The API here
00212     does not support that kind of protection.  This also affects parse()
00213     since it can call parse_multipart().
00214 
00215     """
00216     import http.client
00217 
00218     boundary = ""
00219     if 'boundary' in pdict:
00220         boundary = pdict['boundary']
00221     if not valid_boundary(boundary):
00222         raise ValueError('Invalid boundary in multipart form: %r'
00223                             % (boundary,))
00224 
00225     nextpart = "--" + boundary
00226     lastpart = "--" + boundary + "--"
00227     partdict = {}
00228     terminator = ""
00229 
00230     while terminator != lastpart:
00231         bytes = -1
00232         data = None
00233         if terminator:
00234             # At start of next part.  Read headers first.
00235             headers = http.client.parse_headers(fp)
00236             clength = headers.get('content-length')
00237             if clength:
00238                 try:
00239                     bytes = int(clength)
00240                 except ValueError:
00241                     pass
00242             if bytes > 0:
00243                 if maxlen and bytes > maxlen:
00244                     raise ValueError('Maximum content length exceeded')
00245                 data = fp.read(bytes)
00246             else:
00247                 data = ""
00248         # Read lines until end of part.
00249         lines = []
00250         while 1:
00251             line = fp.readline()
00252             if not line:
00253                 terminator = lastpart # End outer loop
00254                 break
00255             if line.startswith("--"):
00256                 terminator = line.rstrip()
00257                 if terminator in (nextpart, lastpart):
00258                     break
00259             lines.append(line)
00260         # Done with part.
00261         if data is None:
00262             continue
00263         if bytes < 0:
00264             if lines:
00265                 # Strip final line terminator
00266                 line = lines[-1]
00267                 if line[-2:] == "\r\n":
00268                     line = line[:-2]
00269                 elif line[-1:] == "\n":
00270                     line = line[:-1]
00271                 lines[-1] = line
00272                 data = "".join(lines)
00273         line = headers['content-disposition']
00274         if not line:
00275             continue
00276         key, params = parse_header(line)
00277         if key != 'form-data':
00278             continue
00279         if 'name' in params:
00280             name = params['name']
00281         else:
00282             continue
00283         if name in partdict:
00284             partdict[name].append(data)
00285         else:
00286             partdict[name] = [data]
00287 
00288     return partdict
00289 

Here is the call graph for this function:

Here is the caller graph for this function:

def cgi.parse_qs (   qs,
  keep_blank_values = 0,
  strict_parsing = 0 
)
Parse a query given as a string argument.

Definition at line 178 of file cgi.py.

00178 
00179 def parse_qs(qs, keep_blank_values=0, strict_parsing=0):
00180     """Parse a query given as a string argument."""
00181     warn("cgi.parse_qs is deprecated, use urllib.parse.parse_qs instead",
00182          DeprecationWarning, 2)
00183     return urllib.parse.parse_qs(qs, keep_blank_values, strict_parsing)

Here is the call graph for this function:

Here is the caller graph for this function:

def cgi.parse_qsl (   qs,
  keep_blank_values = 0,
  strict_parsing = 0 
)
Parse a query given as a string argument.

Definition at line 184 of file cgi.py.

00184 
00185 def parse_qsl(qs, keep_blank_values=0, strict_parsing=0):
00186     """Parse a query given as a string argument."""
00187     warn("cgi.parse_qsl is deprecated, use urllib.parse.parse_qsl instead",
00188          DeprecationWarning, 2)
00189     return urllib.parse.parse_qsl(qs, keep_blank_values, strict_parsing)

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 949 of file cgi.py.

00949 
00950 def print_arguments():
00951     print()
00952     print("<H3>Command Line Arguments:</H3>")
00953     print()
00954     print(sys.argv)
00955     print()

Here is the caller graph for this function:

Dump the current directory as HTML.

Definition at line 937 of file cgi.py.

00937 
00938 def print_directory():
00939     """Dump the current directory as HTML."""
00940     print()
00941     print("<H3>Current Working Directory:</H3>")
00942     try:
00943         pwd = os.getcwd()
00944     except os.error as msg:
00945         print("os.error:", html.escape(str(msg)))
00946     else:
00947         print(html.escape(pwd))
00948     print()

Here is the caller graph for this function:

def cgi.print_environ (   environ = os.environ)
Dump the shell environment as HTML.

Definition at line 910 of file cgi.py.

00910 
00911 def print_environ(environ=os.environ):
00912     """Dump the shell environment as HTML."""
00913     keys = sorted(environ.keys())
00914     print()
00915     print("<H3>Shell Environment:</H3>")
00916     print("<DL>")
00917     for key in keys:
00918         print("<DT>", html.escape(key), "<DD>", html.escape(environ[key]))
00919     print("</DL>")
00920     print()

Here is the call graph for this function:

Here is the caller graph for this function:

Dump a list of environment variables used by CGI as HTML.

Definition at line 956 of file cgi.py.

00956 
00957 def print_environ_usage():
00958     """Dump a list of environment variables used by CGI as HTML."""
00959     print("""
00960 <H3>These environment variables could have been set:</H3>
00961 <UL>
00962 <LI>AUTH_TYPE
00963 <LI>CONTENT_LENGTH
00964 <LI>CONTENT_TYPE
00965 <LI>DATE_GMT
00966 <LI>DATE_LOCAL
00967 <LI>DOCUMENT_NAME
00968 <LI>DOCUMENT_ROOT
00969 <LI>DOCUMENT_URI
00970 <LI>GATEWAY_INTERFACE
00971 <LI>LAST_MODIFIED
00972 <LI>PATH
00973 <LI>PATH_INFO
00974 <LI>PATH_TRANSLATED
00975 <LI>QUERY_STRING
00976 <LI>REMOTE_ADDR
00977 <LI>REMOTE_HOST
00978 <LI>REMOTE_IDENT
00979 <LI>REMOTE_USER
00980 <LI>REQUEST_METHOD
00981 <LI>SCRIPT_NAME
00982 <LI>SERVER_NAME
00983 <LI>SERVER_PORT
00984 <LI>SERVER_PROTOCOL
00985 <LI>SERVER_ROOT
00986 <LI>SERVER_SOFTWARE
00987 </UL>
00988 In addition, HTTP headers sent by the server may be passed in the
00989 environment as well.  Here are some common variable names:
00990 <UL>
00991 <LI>HTTP_ACCEPT
00992 <LI>HTTP_CONNECTION
00993 <LI>HTTP_HOST
00994 <LI>HTTP_PRAGMA
00995 <LI>HTTP_REFERER
00996 <LI>HTTP_USER_AGENT
00997 </UL>
00998 """)
00999 
01000 
01001 # Utilities
01002 # =========

Here is the caller graph for this function:

def cgi.print_exception (   type = None,
  value = None,
  tb = None,
  limit = None 
)

Definition at line 896 of file cgi.py.

00896 
00897 def print_exception(type=None, value=None, tb=None, limit=None):
00898     if type is None:
00899         type, value, tb = sys.exc_info()
00900     import traceback
00901     print()
00902     print("<H3>Traceback (most recent call last):</H3>")
00903     list = traceback.format_tb(tb, limit) + \
00904            traceback.format_exception_only(type, value)
00905     print("<PRE>%s<B>%s</B></PRE>" % (
00906         html.escape("".join(list[:-1])),
00907         html.escape(list[-1]),
00908         ))
00909     del tb

Here is the call graph for this function:

Here is the caller graph for this function:

def cgi.print_form (   form)
Dump the contents of a form as HTML.

Definition at line 921 of file cgi.py.

00921 
00922 def print_form(form):
00923     """Dump the contents of a form as HTML."""
00924     keys = sorted(form.keys())
00925     print()
00926     print("<H3>Form Contents:</H3>")
00927     if not keys:
00928         print("<P>No form fields.")
00929     print("<DL>")
00930     for key in keys:
00931         print("<DT>" + html.escape(key) + ":", end=' ')
00932         value = form[key]
00933         print("<i>" + html.escape(repr(type(value))) + "</i>")
00934         print("<DD>" + html.escape(repr(value)))
00935     print("</DL>")
00936     print()

Here is the call graph for this function:

Here is the caller graph for this function:

def cgi.test (   environ = os.environ)
Robust test CGI script, usable as main program.

Write minimal HTTP headers and dump all information provided to
the script in HTML form.

Definition at line 857 of file cgi.py.

00857 
00858 def test(environ=os.environ):
00859     """Robust test CGI script, usable as main program.
00860 
00861     Write minimal HTTP headers and dump all information provided to
00862     the script in HTML form.
00863 
00864     """
00865     print("Content-type: text/html")
00866     print()
00867     sys.stderr = sys.stdout
00868     try:
00869         form = FieldStorage()   # Replace with other classes to test those
00870         print_directory()
00871         print_arguments()
00872         print_form(form)
00873         print_environ(environ)
00874         print_environ_usage()
00875         def f():
00876             exec("testing print_exception() -- <I>italics?</I>")
00877         def g(f=f):
00878             f()
00879         print("<H3>What follows is a test, not an actual exception:</H3>")
00880         g()
00881     except:
00882         print_exception()
00883 
00884     print("<H1>Second try with a small maxlen...</H1>")
00885 
00886     global maxlen
00887     maxlen = 50
00888     try:
00889         form = FieldStorage()   # Replace with other classes to test those
00890         print_directory()
00891         print_arguments()
00892         print_form(form)
00893         print_environ(environ)
00894     except:
00895         print_exception()

Here is the call graph for this function:

def cgi.valid_boundary (   s,
  _vb_pattern = None 
)

Definition at line 1015 of file cgi.py.

01015 
01016 def valid_boundary(s, _vb_pattern=None):
01017     import re
01018     if isinstance(s, bytes):
01019         _vb_pattern = b"^[ -~]{0,200}[!-~]$"
01020     else:
01021         _vb_pattern = "^[ -~]{0,200}[!-~]$"
01022     return re.match(_vb_pattern, s)
01023 
01024 # Invoke mainline
01025 # ===============
01026 
# Call test() when this file is run as a script (not imported as a module)

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

Initial value:
00001 ["MiniFieldStorage", "FieldStorage",
00002            "parse", "parse_qs", "parse_qsl", "parse_multipart",
00003            "parse_header", "print_exception", "print_environ",
00004            "print_form", "print_directory", "print_arguments",
00005            "print_environ_usage", "escape"]

Definition at line 44 of file cgi.py.

Definition at line 28 of file cgi.py.

Definition at line 99 of file cgi.py.

Definition at line 53 of file cgi.py.

cgi.logfp = None

Definition at line 54 of file cgi.py.

Definition at line 107 of file cgi.py.