Vega strike Python Modules doc  0.5.1
Documentation of the " Modules " folder of Vega strike
 All Data Structures Namespaces Files Functions Variables
cgi Namespace Reference

Data Structures

class  MiniFieldStorage
 
class  FieldStorage
 
class  FormContentDict
 
class  SvFormContentDict
 
class  InterpFormContentDict
 
class  FormContent
 

Functions

def initlog
 
def dolog
 
def nolog
 
def parse
 
def parse_qs
 
def parse_qsl
 
def parse_multipart
 
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.dolog (   fmt,
  args 
)
Write a log message to the log file.  See initlog() for docs.

Definition at line 93 of file cgi.py.

93 
94 def dolog(fmt, *args):
95  """Write a log message to the log file. See initlog() for docs."""
96  logfp.write(fmt%args + "\n")
def cgi.escape (   s,
  quote = None 
)
Replace special characters '&', '<' and '>' by SGML entities.

Definition at line 1022 of file cgi.py.

1023 def escape(s, quote=None):
1024  """Replace special characters '&', '<' and '>' by SGML entities."""
1025  s = s.replace("&", "&amp;") # Must be done first!
1026  s = s.replace("<", "&lt;")
1027  s = s.replace(">", "&gt;")
1028  if quote:
1029  s = s.replace('"', "&quot;")
1030  return s
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 58 of file cgi.py.

References aifc.open().

58 
59 def initlog(*allargs):
60  """Write a log message, if there is a log file.
61 
62  Even though this function is called initlog(), you should always
63  use log(); log is a variable that is set either to initlog
64  (initially), to dolog (once the log file has been opened), or to
65  nolog (when logging is disabled).
66 
67  The first argument is a format string; the remaining arguments (if
68  any) are arguments to the % operator, so e.g.
69  log("%s: %s", "a", "b")
70  will write "a: b" to the log file, followed by a newline.
71 
72  If the global logfp is not None, it should be a file object to
73  which log data is written.
74 
75  If the global logfp is None, the global logfile may be a string
76  giving a filename to open, in append mode. This file should be
77  world writable!!! If the file can't be opened, logging is
78  silently disabled (since there is no safe place where we could
79  send an error message).
80 
81  """
82  global logfp, log
83  if logfile and not logfp:
84  try:
85  logfp = open(logfile, "a")
86  except IOError:
87  pass
88  if not logfp:
89  log = nolog
90  else:
91  log = dolog
92  apply(log, allargs)
def cgi.nolog (   allargs)
Dummy function, assigned to log when logging is disabled.

Definition at line 97 of file cgi.py.

97 
98 def nolog(*allargs):
99  """Dummy function, assigned to log when logging is disabled."""
100  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

    environ         : environment dictionary; default: os.environ

    keep_blank_values: flag indicating whether blank values in
        URL 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 111 of file cgi.py.

References parse_header(), parse_multipart(), and parse_qs().

112 def parse(fp=None, environ=os.environ, keep_blank_values=0, strict_parsing=0):
113  """Parse a query in the environment or from a file (default stdin)
114 
115  Arguments, all optional:
116 
117  fp : file pointer; default: sys.stdin
118 
119  environ : environment dictionary; default: os.environ
120 
121  keep_blank_values: flag indicating whether blank values in
122  URL encoded forms should be treated as blank strings.
123  A true value indicates that blanks should be retained as
124  blank strings. The default false value indicates that
125  blank values are to be ignored and treated as if they were
126  not included.
127 
128  strict_parsing: flag indicating what to do with parsing errors.
129  If false (the default), errors are silently ignored.
130  If true, errors raise a ValueError exception.
131  """
132  if not fp:
133  fp = sys.stdin
134  if not environ.has_key('REQUEST_METHOD'):
135  environ['REQUEST_METHOD'] = 'GET' # For testing stand-alone
136  if environ['REQUEST_METHOD'] == 'POST':
137  ctype, pdict = parse_header(environ['CONTENT_TYPE'])
138  if ctype == 'multipart/form-data':
139  return parse_multipart(fp, pdict)
140  elif ctype == 'application/x-www-form-urlencoded':
141  clength = int(environ['CONTENT_LENGTH'])
142  if maxlen and clength > maxlen:
143  raise ValueError, 'Maximum content length exceeded'
144  qs = fp.read(clength)
145  else:
146  qs = '' # Unknown content-type
147  if environ.has_key('QUERY_STRING'):
148  if qs: qs = qs + '&'
149  qs = qs + environ['QUERY_STRING']
150  elif sys.argv[1:]:
151  if qs: qs = qs + '&'
152  qs = qs + sys.argv[1]
153  environ['QUERY_STRING'] = qs # XXX Shouldn't, really
154  elif environ.has_key('QUERY_STRING'):
155  qs = environ['QUERY_STRING']
156  else:
157  if sys.argv[1:]:
158  qs = sys.argv[1]
159  else:
160  qs = ""
161  environ['QUERY_STRING'] = qs # XXX Shouldn't, really
162  return parse_qs(qs, keep_blank_values, strict_parsing)
163 
def cgi.parse_header (   line)
Parse a Content-type like header.

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

Definition at line 319 of file cgi.py.

References string.lower(), and string.strip().

320 def parse_header(line):
321  """Parse a Content-type like header.
322 
323  Return the main content-type and a dictionary of options.
324 
325  """
326  plist = map(lambda x: x.strip(), line.split(';'))
327  key = plist[0].lower()
328  del plist[0]
329  pdict = {}
330  for p in plist:
331  i = p.find('=')
332  if i >= 0:
333  name = p[:i].strip().lower()
334  value = p[i+1:].strip()
335  if len(value) >= 2 and value[0] == value[-1] == '"':
336  value = value[1:-1]
337  pdict[name] = value
338  return key, pdict
339 
340 
341 # Classes for field storage
342 # =========================
def cgi.parse_multipart (   fp,
  pdict 
)
Parse multipart input.

Arguments:
fp   : input file
pdict: dictionary containing other parameters of conten-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.

Definition at line 225 of file cgi.py.

References reconvert.append, dospath.join(), parse_header(), and valid_boundary().

226 def parse_multipart(fp, pdict):
227  """Parse multipart input.
228 
229  Arguments:
230  fp : input file
231  pdict: dictionary containing other parameters of conten-type header
232 
233  Returns a dictionary just like parse_qs(): keys are the field names, each
234  value is a list of values for that field. This is easy to use but not
235  much good if you are expecting megabytes to be uploaded -- in that case,
236  use the FieldStorage class instead which is much more flexible. Note
237  that content-type is the raw, unparsed contents of the content-type
238  header.
239 
240  XXX This does not parse nested multipart parts -- use FieldStorage for
241  that.
242 
243  XXX This should really be subsumed by FieldStorage altogether -- no
244  point in having two implementations of the same parsing algorithm.
245 
246  """
247  boundary = ""
248  if pdict.has_key('boundary'):
249  boundary = pdict['boundary']
250  if not valid_boundary(boundary):
251  raise ValueError, ('Invalid boundary in multipart form: %s'
252  % `boundary`)
253 
254  nextpart = "--" + boundary
255  lastpart = "--" + boundary + "--"
256  partdict = {}
257  terminator = ""
258 
259  while terminator != lastpart:
260  bytes = -1
261  data = None
262  if terminator:
263  # At start of next part. Read headers first.
264  headers = mimetools.Message(fp)
265  clength = headers.getheader('content-length')
266  if clength:
267  try:
268  bytes = int(clength)
269  except ValueError:
270  pass
271  if bytes > 0:
272  if maxlen and bytes > maxlen:
273  raise ValueError, 'Maximum content length exceeded'
274  data = fp.read(bytes)
275  else:
276  data = ""
277  # Read lines until end of part.
278  lines = []
279  while 1:
280  line = fp.readline()
281  if not line:
282  terminator = lastpart # End outer loop
283  break
284  if line[:2] == "--":
285  terminator = line.strip()
286  if terminator in (nextpart, lastpart):
287  break
288  lines.append(line)
289  # Done with part.
290  if data is None:
291  continue
292  if bytes < 0:
293  if lines:
294  # Strip final line terminator
295  line = lines[-1]
296  if line[-2:] == "\r\n":
297  line = line[:-2]
298  elif line[-1:] == "\n":
299  line = line[:-1]
300  lines[-1] = line
301  data = "".join(lines)
302  line = headers['content-disposition']
303  if not line:
304  continue
305  key, params = parse_header(line)
306  if key != 'form-data':
307  continue
308  if params.has_key('name'):
309  name = params['name']
310  else:
311  continue
312  if partdict.has_key(name):
313  partdict[name].append(data)
314  else:
315  partdict[name] = [data]
316 
317  return partdict
318 
def cgi.parse_qs (   qs,
  keep_blank_values = 0,
  strict_parsing = 0 
)
Parse a query given as a string argument.

    Arguments:

    qs: URL-encoded query string to be parsed

    keep_blank_values: flag indicating whether blank values in
        URL encoded queries 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 164 of file cgi.py.

References reconvert.append, and parse_qsl().

165 def parse_qs(qs, keep_blank_values=0, strict_parsing=0):
166  """Parse a query given as a string argument.
167 
168  Arguments:
169 
170  qs: URL-encoded query string to be parsed
171 
172  keep_blank_values: flag indicating whether blank values in
173  URL encoded queries should be treated as blank strings.
174  A true value indicates that blanks should be retained as
175  blank strings. The default false value indicates that
176  blank values are to be ignored and treated as if they were
177  not included.
178 
179  strict_parsing: flag indicating what to do with parsing errors.
180  If false (the default), errors are silently ignored.
181  If true, errors raise a ValueError exception.
182  """
183  dict = {}
184  for name, value in parse_qsl(qs, keep_blank_values, strict_parsing):
185  if dict.has_key(name):
186  dict[name].append(value)
187  else:
188  dict[name] = [value]
189  return dict
def cgi.parse_qsl (   qs,
  keep_blank_values = 0,
  strict_parsing = 0 
)
Parse a query given as a string argument.

Arguments:

qs: URL-encoded query string to be parsed

keep_blank_values: flag indicating whether blank values in
    URL encoded queries 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.

Returns a list, as G-d intended.

Definition at line 190 of file cgi.py.

References pydoc.replace(), and urllib.unquote().

191 def parse_qsl(qs, keep_blank_values=0, strict_parsing=0):
192  """Parse a query given as a string argument.
193 
194  Arguments:
195 
196  qs: URL-encoded query string to be parsed
197 
198  keep_blank_values: flag indicating whether blank values in
199  URL encoded queries should be treated as blank strings. A
200  true value indicates that blanks should be retained as blank
201  strings. The default false value indicates that blank values
202  are to be ignored and treated as if they were not included.
203 
204  strict_parsing: flag indicating what to do with parsing errors. If
205  false (the default), errors are silently ignored. If true,
206  errors raise a ValueError exception.
207 
208  Returns a list, as G-d intended.
209  """
210  pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
211  r = []
212  for name_value in pairs:
213  nv = name_value.split('=', 1)
214  if len(nv) != 2:
215  if strict_parsing:
216  raise ValueError, "bad query field: %s" % `name_value`
217  continue
218  if len(nv[1]) or keep_blank_values:
219  name = urllib.unquote(nv[0].replace('+', ' '))
220  value = urllib.unquote(nv[1].replace('+', ' '))
221  r.append((name, value))
222 
223  return r
224 
def cgi.print_arguments ( )

Definition at line 968 of file cgi.py.

969 def print_arguments():
970  print
971  print "<H3>Command Line Arguments:</H3>"
972  print
973  print sys.argv
974  print
def cgi.print_directory ( )
Dump the current directory as HTML.

Definition at line 956 of file cgi.py.

References escape(), and locale.str().

957 def print_directory():
958  """Dump the current directory as HTML."""
959  print
960  print "<H3>Current Working Directory:</H3>"
961  try:
962  pwd = os.getcwd()
963  except os.error, msg:
964  print "os.error:", escape(str(msg))
965  else:
966  print escape(pwd)
967  print
def cgi.print_environ (   environ = os.environ)
Dump the shell environment as HTML.

Definition at line 927 of file cgi.py.

References escape().

928 def print_environ(environ=os.environ):
929  """Dump the shell environment as HTML."""
930  keys = environ.keys()
931  keys.sort()
932  print
933  print "<H3>Shell Environment:</H3>"
934  print "<DL>"
935  for key in keys:
936  print "<DT>", escape(key), "<DD>", escape(environ[key])
937  print "</DL>"
938  print
def cgi.print_environ_usage ( )
Dump a list of environment variables used by CGI as HTML.

Definition at line 975 of file cgi.py.

976 def print_environ_usage():
977  """Dump a list of environment variables used by CGI as HTML."""
978  print """
979 <H3>These environment variables could have been set:</H3>
980 <UL>
981 <LI>AUTH_TYPE
982 <LI>CONTENT_LENGTH
983 <LI>CONTENT_TYPE
984 <LI>DATE_GMT
985 <LI>DATE_LOCAL
986 <LI>DOCUMENT_NAME
987 <LI>DOCUMENT_ROOT
988 <LI>DOCUMENT_URI
989 <LI>GATEWAY_INTERFACE
990 <LI>LAST_MODIFIED
991 <LI>PATH
992 <LI>PATH_INFO
993 <LI>PATH_TRANSLATED
994 <LI>QUERY_STRING
995 <LI>REMOTE_ADDR
996 <LI>REMOTE_HOST
997 <LI>REMOTE_IDENT
998 <LI>REMOTE_USER
999 <LI>REQUEST_METHOD
1000 <LI>SCRIPT_NAME
1001 <LI>SERVER_NAME
1002 <LI>SERVER_PORT
1003 <LI>SERVER_PROTOCOL
1004 <LI>SERVER_ROOT
1005 <LI>SERVER_SOFTWARE
1006 </UL>
1007 In addition, HTTP headers sent by the server may be passed in the
1008 environment as well. Here are some common variable names:
1009 <UL>
1010 <LI>HTTP_ACCEPT
1011 <LI>HTTP_CONNECTION
1012 <LI>HTTP_HOST
1013 <LI>HTTP_PRAGMA
1014 <LI>HTTP_REFERER
1015 <LI>HTTP_USER_AGENT
1016 </UL>
1017 """
1018 
1019 
1020 # Utilities
1021 # =========
def cgi.print_exception (   type = None,
  value = None,
  tb = None,
  limit = None 
)

Definition at line 913 of file cgi.py.

References escape(), traceback.format_exception_only(), traceback.format_tb(), and dospath.join().

914 def print_exception(type=None, value=None, tb=None, limit=None):
915  if type is None:
916  type, value, tb = sys.exc_info()
917  import traceback
918  print
919  print "<H3>Traceback (most recent call last):</H3>"
920  list = traceback.format_tb(tb, limit) + \
922  print "<PRE>%s<B>%s</B></PRE>" % (
923  escape("".join(list[:-1])),
924  escape(list[-1]),
925  )
926  del tb
def cgi.print_form (   form)
Dump the contents of a form as HTML.

Definition at line 939 of file cgi.py.

References escape().

940 def print_form(form):
941  """Dump the contents of a form as HTML."""
942  keys = form.keys()
943  keys.sort()
944  print
945  print "<H3>Form Contents:</H3>"
946  if not keys:
947  print "<P>No form fields."
948  print "<DL>"
949  for key in keys:
950  print "<DT>" + escape(key) + ":",
951  value = form[key]
952  print "<i>" + escape(`type(value)`) + "</i>"
953  print "<DD>" + escape(`value`)
954  print "</DL>"
955  print
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 873 of file cgi.py.

References aifc.f, aifc.g, print_arguments(), print_directory(), print_environ(), print_environ_usage(), print_exception(), and print_form().

874 def test(environ=os.environ):
875  """Robust test CGI script, usable as main program.
876 
877  Write minimal HTTP headers and dump all information provided to
878  the script in HTML form.
879 
880  """
881  import traceback
882  print "Content-type: text/html"
883  print
884  sys.stderr = sys.stdout
885  try:
886  form = FieldStorage() # Replace with other classes to test those
889  print_form(form)
890  print_environ(environ)
892  def f():
893  exec "testing print_exception() -- <I>italics?</I>"
894  def g(f=f):
895  f()
896  print "<H3>What follows is a test, not an actual exception:</H3>"
897  g()
898  except:
900 
901  print "<H1>Second try with a small maxlen...</H1>"
902 
903  global maxlen
904  maxlen = 50
905  try:
906  form = FieldStorage() # Replace with other classes to test those
909  print_form(form)
910  print_environ(environ)
911  except:
def cgi.valid_boundary (   s,
  _vb_pattern = "^[ -~]{0 
)

Definition at line 1031 of file cgi.py.

References test().

1032 def valid_boundary(s, _vb_pattern="^[ -~]{0,200}[!-~]$"):
1033  import re
1034  return re.match(_vb_pattern, s)
1035 
1036 # Invoke mainline
1037 # ===============
1038 
# Call test() when this file is run as a script (not imported as a module)

Variable Documentation

list __all__
Initial value:
1 = ["MiniFieldStorage", "FieldStorage", "FormContentDict",
2  "SvFormContentDict", "InterpFormContentDict", "FormContent",
3  "parse", "parse_qs", "parse_qsl", "parse_multipart",
4  "parse_header", "print_exception", "print_environ",
5  "print_form", "print_directory", "print_arguments",
6  "print_environ_usage", "escape"]

Definition at line 45 of file cgi.py.

string __version__ = "2.6"

Definition at line 31 of file cgi.py.

log = initlog

Definition at line 101 of file cgi.py.

string logfile = ""

Definition at line 55 of file cgi.py.

logfp = None

Definition at line 56 of file cgi.py.

int maxlen = 0

Definition at line 109 of file cgi.py.