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