Debian Codegraph @

cpython27/Lib/cgi.py

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