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