Guido van Rossum | 152f9d9 | 1997-02-18 16:55:33 +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 | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 3 | """Support module for CGI (Common Gateway Interface) scripts. |
Guido van Rossum | 1c9daa8 | 1995-09-18 21:52:37 +0000 | [diff] [blame] | 4 | |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 5 | This module defines a number of utilities for use by CGI scripts |
| 6 | written in Python. |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 7 | |
| 8 | |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 9 | Introduction |
| 10 | ------------ |
| 11 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 12 | A CGI script is invoked by an HTTP server, usually to process user |
| 13 | input submitted through an HTML <FORM> or <ISINPUT> element. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 14 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 15 | Most often, CGI scripts live in the server's special cgi-bin |
| 16 | directory. The HTTP server places all sorts of information about the |
| 17 | request (such as the client's hostname, the requested URL, the query |
| 18 | string, and lots of other goodies) in the script's shell environment, |
| 19 | executes the script, and sends the script's output back to the client. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 20 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 21 | The script's input is connected to the client too, and sometimes the |
| 22 | form data is read this way; at other times the form data is passed via |
| 23 | the "query string" part of the URL. This module (cgi.py) is intended |
| 24 | to take care of the different cases and provide a simpler interface to |
| 25 | the Python script. It also provides a number of utilities that help |
| 26 | in debugging scripts, and the latest addition is support for file |
| 27 | uploads from a form (if your browser supports it -- Grail 0.3 and |
| 28 | Netscape 2.0 do). |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 29 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 30 | The output of a CGI script should consist of two sections, separated |
| 31 | by a blank line. The first section contains a number of headers, |
| 32 | telling the client what kind of data is following. Python code to |
| 33 | generate a minimal header section looks like this: |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 34 | |
Guido van Rossum | 243ddcd | 1996-03-07 06:33:07 +0000 | [diff] [blame] | 35 | print "Content-type: text/html" # HTML is following |
| 36 | print # blank line, end of headers |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 37 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 38 | The second section is usually HTML, which allows the client software |
| 39 | to display nicely formatted text with header, in-line images, etc. |
| 40 | Here's Python code that prints a simple piece of HTML: |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 41 | |
| 42 | print "<TITLE>CGI script output</TITLE>" |
| 43 | print "<H1>This is my first CGI script</H1>" |
| 44 | print "Hello, world!" |
| 45 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 46 | (It may not be fully legal HTML according to the letter of the |
| 47 | standard, but any browser will understand it.) |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 48 | |
| 49 | |
| 50 | Using the cgi module |
| 51 | -------------------- |
| 52 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 53 | Begin by writing "import cgi". Don't use "from cgi import *" -- the |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 54 | module defines all sorts of names for its own use or for backward |
| 55 | compatibility that you don't want in your namespace. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 56 | |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 57 | It's best to use the FieldStorage class. The other classes define in this |
| 58 | module are provided mostly for backward compatibility. Instantiate it |
| 59 | exactly once, without arguments. This reads the form contents from |
| 60 | standard input or the environment (depending on the value of various |
| 61 | environment variables set according to the CGI standard). Since it may |
| 62 | consume standard input, it should be instantiated only once. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 63 | |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 64 | The FieldStorage instance can be accessed as if it were a Python |
| 65 | dictionary. For instance, the following code (which assumes that the |
| 66 | Content-type header and blank line have already been printed) checks that |
| 67 | the fields "name" and "addr" are both set to a non-empty string: |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 68 | |
Guido van Rossum | 503e50b | 1996-05-28 22:57:20 +0000 | [diff] [blame] | 69 | form = cgi.FieldStorage() |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 70 | form_ok = 0 |
| 71 | if form.has_key("name") and form.has_key("addr"): |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 72 | if form["name"].value != "" and form["addr"].value != "": |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 73 | form_ok = 1 |
| 74 | if not form_ok: |
| 75 | print "<H1>Error</H1>" |
| 76 | print "Please fill in the name and addr fields." |
| 77 | return |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 78 | ...further form processing here... |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 79 | |
Guido van Rossum | 4032c2c | 1996-03-09 04:04:35 +0000 | [diff] [blame] | 80 | Here the fields, accessed through form[key], are themselves instances |
| 81 | of FieldStorage (or MiniFieldStorage, depending on the form encoding). |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 82 | |
Guido van Rossum | 4032c2c | 1996-03-09 04:04:35 +0000 | [diff] [blame] | 83 | If the submitted form data contains more than one field with the same |
| 84 | name, the object retrieved by form[key] is not a (Mini)FieldStorage |
| 85 | instance but a list of such instances. If you expect this possibility |
| 86 | (i.e., when your HTML form comtains multiple fields with the same |
| 87 | name), use the type() function to determine whether you have a single |
| 88 | instance or a list of instances. For example, here's code that |
| 89 | concatenates any number of username fields, separated by commas: |
| 90 | |
| 91 | username = form["username"] |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 92 | if type(username) is type([]): |
| 93 | # Multiple username fields specified |
| 94 | usernames = "" |
| 95 | for item in username: |
| 96 | if usernames: |
| 97 | # Next item -- insert comma |
| 98 | usernames = usernames + "," + item.value |
| 99 | else: |
| 100 | # First item -- don't insert comma |
| 101 | usernames = item.value |
| 102 | else: |
| 103 | # Single username field specified |
Guido van Rossum | 4032c2c | 1996-03-09 04:04:35 +0000 | [diff] [blame] | 104 | usernames = username.value |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 105 | |
| 106 | If a field represents an uploaded file, the value attribute reads the |
| 107 | entire file in memory as a string. This may not be what you want. You can |
| 108 | test for an uploaded file by testing either the filename attribute or the |
| 109 | file attribute. You can then read the data at leasure from the file |
| 110 | attribute: |
| 111 | |
| 112 | fileitem = form["userfile"] |
| 113 | if fileitem.file: |
| 114 | # It's an uploaded file; count lines |
| 115 | linecount = 0 |
| 116 | while 1: |
| 117 | line = fileitem.file.readline() |
| 118 | if not line: break |
| 119 | linecount = linecount + 1 |
| 120 | |
Guido van Rossum | 4032c2c | 1996-03-09 04:04:35 +0000 | [diff] [blame] | 121 | The file upload draft standard entertains the possibility of uploading |
| 122 | multiple files from one field (using a recursive multipart/* |
| 123 | encoding). When this occurs, the item will be a dictionary-like |
| 124 | FieldStorage item. This can be determined by testing its type |
| 125 | attribute, which should have the value "multipart/form-data" (or |
| 126 | perhaps another string beginning with "multipart/"). It this case, it |
| 127 | can be iterated over recursively just like the top-level form object. |
| 128 | |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 129 | When a form is submitted in the "old" format (as the query string or as a |
| 130 | single data part of type application/x-www-form-urlencoded), the items |
| 131 | will actually be instances of the class MiniFieldStorage. In this case, |
| 132 | the list, file and filename attributes are always None. |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 133 | |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 134 | |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 135 | Old classes |
| 136 | ----------- |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 137 | |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 138 | These classes, present in earlier versions of the cgi module, are still |
Guido van Rossum | 16d5b11 | 1996-10-24 14:44:32 +0000 | [diff] [blame] | 139 | supported for backward compatibility. New applications should use the |
| 140 | FieldStorage class. |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 141 | |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 142 | SvFormContentDict: single value form content as dictionary; assumes each |
| 143 | field name occurs in the form only once. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 144 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 145 | FormContentDict: multiple value form content as dictionary (the form |
| 146 | items are lists of values). Useful if your form contains multiple |
| 147 | fields with the same name. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 148 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 149 | Other classes (FormContent, InterpFormContentDict) are present for |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 150 | backwards compatibility with really old applications only. If you still |
| 151 | use these and would be inconvenienced when they disappeared from a next |
| 152 | version of this module, drop me a note. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 153 | |
| 154 | |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 155 | Functions |
| 156 | --------- |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 157 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 158 | These are useful if you want more control, or if you want to employ |
| 159 | some of the algorithms implemented in this module in other |
| 160 | circumstances. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 161 | |
Guido van Rossum | e08c04c | 1996-11-11 19:29:11 +0000 | [diff] [blame] | 162 | parse(fp, [environ, [keep_blank_values, [strict_parsing]]]): parse a |
| 163 | form into a Python dictionary. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 164 | |
Guido van Rossum | e08c04c | 1996-11-11 19:29:11 +0000 | [diff] [blame] | 165 | parse_qs(qs, [keep_blank_values, [strict_parsing]]): parse a query |
| 166 | string (data of type application/x-www-form-urlencoded). |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 167 | |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 168 | parse_multipart(fp, pdict): parse input of type multipart/form-data (for |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 169 | file uploads). |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 170 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 171 | parse_header(string): parse a header like Content-type into a main |
| 172 | value and a dictionary of parameters. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 173 | |
| 174 | test(): complete test program. |
| 175 | |
| 176 | print_environ(): format the shell environment in HTML. |
| 177 | |
| 178 | print_form(form): format a form in HTML. |
| 179 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 180 | print_environ_usage(): print a list of useful environment variables in |
| 181 | HTML. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 182 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 183 | escape(): convert the characters "&", "<" and ">" to HTML-safe |
| 184 | sequences. Use this if you need to display text that might contain |
| 185 | such characters in HTML. To translate URLs for inclusion in the HREF |
| 186 | attribute of an <A> tag, use urllib.quote(). |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 187 | |
Guido van Rossum | c204c70 | 1996-09-05 19:07:11 +0000 | [diff] [blame] | 188 | log(fmt, ...): write a line to a log file; see docs for initlog(). |
| 189 | |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 190 | |
| 191 | Caring about security |
| 192 | --------------------- |
| 193 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 194 | There's one important rule: if you invoke an external program (e.g. |
| 195 | via the os.system() or os.popen() functions), make very sure you don't |
| 196 | pass arbitrary strings received from the client to the shell. This is |
| 197 | a well-known security hole whereby clever hackers anywhere on the web |
| 198 | can exploit a gullible CGI script to invoke arbitrary shell commands. |
| 199 | Even parts of the URL or field names cannot be trusted, since the |
| 200 | request doesn't have to come from your form! |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 201 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 202 | To be on the safe side, if you must pass a string gotten from a form |
| 203 | to a shell command, you should make sure the string contains only |
| 204 | alphanumeric characters, dashes, underscores, and periods. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 205 | |
| 206 | |
| 207 | Installing your CGI script on a Unix system |
| 208 | ------------------------------------------- |
| 209 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 210 | Read the documentation for your HTTP server and check with your local |
| 211 | system administrator to find the directory where CGI scripts should be |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 212 | installed; usually this is in a directory cgi-bin in the server tree. |
| 213 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 214 | Make sure that your script is readable and executable by "others"; the |
| 215 | Unix file mode should be 755 (use "chmod 755 filename"). Make sure |
| 216 | that the first line of the script contains "#!" starting in column 1 |
| 217 | followed by the pathname of the Python interpreter, for instance: |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 218 | |
Guido van Rossum | f06ee5f | 1996-11-27 19:52:01 +0000 | [diff] [blame] | 219 | #! /usr/local/bin/python |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 220 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 221 | Make sure the Python interpreter exists and is executable by "others". |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 222 | |
Guido van Rossum | f06ee5f | 1996-11-27 19:52:01 +0000 | [diff] [blame] | 223 | (Note that it's probably not a good idea to use #! /usr/bin/env python |
| 224 | here, since the Python interpreter may not be on the default path |
| 225 | given to CGI scripts!!!) |
| 226 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 227 | Make sure that any files your script needs to read or write are |
| 228 | readable or writable, respectively, by "others" -- their mode should |
| 229 | be 644 for readable and 666 for writable. This is because, for |
| 230 | security reasons, the HTTP server executes your script as user |
| 231 | "nobody", without any special privileges. It can only read (write, |
| 232 | execute) files that everybody can read (write, execute). The current |
| 233 | directory at execution time is also different (it is usually the |
| 234 | server's cgi-bin directory) and the set of environment variables is |
| 235 | also different from what you get at login. in particular, don't count |
| 236 | on the shell's search path for executables ($PATH) or the Python |
| 237 | module search path ($PYTHONPATH) to be set to anything interesting. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 238 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 239 | If you need to load modules from a directory which is not on Python's |
| 240 | default module search path, you can change the path in your script, |
| 241 | before importing other modules, e.g.: |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 242 | |
| 243 | import sys |
| 244 | sys.path.insert(0, "/usr/home/joe/lib/python") |
| 245 | sys.path.insert(0, "/usr/local/lib/python") |
| 246 | |
| 247 | (This way, the directory inserted last will be searched first!) |
| 248 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 249 | Instructions for non-Unix systems will vary; check your HTTP server's |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 250 | documentation (it will usually have a section on CGI scripts). |
| 251 | |
| 252 | |
| 253 | Testing your CGI script |
| 254 | ----------------------- |
| 255 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 256 | Unfortunately, a CGI script will generally not run when you try it |
| 257 | from the command line, and a script that works perfectly from the |
| 258 | command line may fail mysteriously when run from the server. There's |
| 259 | one reason why you should still test your script from the command |
| 260 | line: if it contains a syntax error, the python interpreter won't |
| 261 | execute it at all, and the HTTP server will most likely send a cryptic |
| 262 | error to the client. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 263 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 264 | Assuming your script has no syntax errors, yet it does not work, you |
| 265 | have no choice but to read the next section: |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 266 | |
| 267 | |
| 268 | Debugging CGI scripts |
| 269 | --------------------- |
| 270 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 271 | First of all, check for trivial installation errors -- reading the |
| 272 | section above on installing your CGI script carefully can save you a |
| 273 | lot of time. If you wonder whether you have understood the |
| 274 | installation procedure correctly, try installing a copy of this module |
| 275 | file (cgi.py) as a CGI script. When invoked as a script, the file |
| 276 | will dump its environment and the contents of the form in HTML form. |
| 277 | Give it the right mode etc, and send it a request. If it's installed |
| 278 | in the standard cgi-bin directory, it should be possible to send it a |
| 279 | request by entering a URL into your browser of the form: |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 280 | |
| 281 | http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home |
| 282 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 283 | If this gives an error of type 404, the server cannot find the script |
| 284 | -- perhaps you need to install it in a different directory. If it |
| 285 | gives another error (e.g. 500), there's an installation problem that |
| 286 | you should fix before trying to go any further. If you get a nicely |
| 287 | formatted listing of the environment and form content (in this |
| 288 | example, the fields should be listed as "addr" with value "At Home" |
| 289 | and "name" with value "Joe Blow"), the cgi.py script has been |
| 290 | installed correctly. If you follow the same procedure for your own |
| 291 | script, you should now be able to debug it. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 292 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 293 | The next step could be to call the cgi module's test() function from |
| 294 | your script: replace its main code with the single statement |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 295 | |
| 296 | cgi.test() |
| 297 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 298 | This should produce the same results as those gotten from installing |
| 299 | the cgi.py file itself. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 300 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 301 | When an ordinary Python script raises an unhandled exception |
| 302 | (e.g. because of a typo in a module name, a file that can't be opened, |
| 303 | etc.), the Python interpreter prints a nice traceback and exits. |
| 304 | While the Python interpreter will still do this when your CGI script |
| 305 | raises an exception, most likely the traceback will end up in one of |
| 306 | the HTTP server's log file, or be discarded altogether. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 307 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 308 | Fortunately, once you have managed to get your script to execute |
| 309 | *some* code, it is easy to catch exceptions and cause a traceback to |
| 310 | be printed. The test() function below in this module is an example. |
| 311 | Here are the rules: |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 312 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 313 | 1. Import the traceback module (before entering the |
| 314 | try-except!) |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 315 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 316 | 2. Make sure you finish printing the headers and the blank |
| 317 | line early |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 318 | |
| 319 | 3. Assign sys.stderr to sys.stdout |
| 320 | |
| 321 | 3. Wrap all remaining code in a try-except statement |
| 322 | |
| 323 | 4. In the except clause, call traceback.print_exc() |
| 324 | |
| 325 | For example: |
| 326 | |
| 327 | import sys |
| 328 | import traceback |
| 329 | print "Content-type: text/html" |
| 330 | print |
| 331 | sys.stderr = sys.stdout |
| 332 | try: |
| 333 | ...your code here... |
| 334 | except: |
| 335 | print "\n\n<PRE>" |
| 336 | traceback.print_exc() |
| 337 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 338 | Notes: The assignment to sys.stderr is needed because the traceback |
| 339 | prints to sys.stderr. The print "\n\n<PRE>" statement is necessary to |
| 340 | disable the word wrapping in HTML. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 341 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 342 | If you suspect that there may be a problem in importing the traceback |
| 343 | module, you can use an even more robust approach (which only uses |
| 344 | built-in modules): |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 345 | |
| 346 | import sys |
| 347 | sys.stderr = sys.stdout |
| 348 | print "Content-type: text/plain" |
| 349 | print |
| 350 | ...your code here... |
| 351 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 352 | This relies on the Python interpreter to print the traceback. The |
| 353 | content type of the output is set to plain text, which disables all |
| 354 | HTML processing. If your script works, the raw HTML will be displayed |
| 355 | by your client. If it raises an exception, most likely after the |
| 356 | first two lines have been printed, a traceback will be displayed. |
| 357 | Because no HTML interpretation is going on, the traceback will |
| 358 | readable. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 359 | |
Guido van Rossum | c204c70 | 1996-09-05 19:07:11 +0000 | [diff] [blame] | 360 | When all else fails, you may want to insert calls to log() to your |
| 361 | program or even to a copy of the cgi.py file. Note that this requires |
| 362 | you to set cgi.logfile to the name of a world-writable file before the |
| 363 | first call to log() is made! |
| 364 | |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 365 | Good luck! |
| 366 | |
| 367 | |
| 368 | Common problems and solutions |
| 369 | ----------------------------- |
| 370 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 371 | - Most HTTP servers buffer the output from CGI scripts until the |
| 372 | script is completed. This means that it is not possible to display a |
| 373 | progress report on the client's display while the script is running. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 374 | |
| 375 | - Check the installation instructions above. |
| 376 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 377 | - Check the HTTP server's log files. ("tail -f logfile" in a separate |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 378 | window may be useful!) |
| 379 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 380 | - Always check a script for syntax errors first, by doing something |
| 381 | like "python script.py". |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 382 | |
| 383 | - When using any of the debugging techniques, don't forget to add |
| 384 | "import sys" to the top of the script. |
| 385 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 386 | - When invoking external programs, make sure they can be found. |
| 387 | Usually, this means using absolute path names -- $PATH is usually not |
| 388 | set to a very useful value in a CGI script. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 389 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 390 | - When reading or writing external files, make sure they can be read |
| 391 | or written by every user on the system. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 392 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 393 | - Don't try to give a CGI script a set-uid mode. This doesn't work on |
| 394 | most systems, and is a security liability as well. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 395 | |
| 396 | |
| 397 | History |
| 398 | ------- |
| 399 | |
Guido van Rossum | 391b4e6 | 1996-03-06 19:11:33 +0000 | [diff] [blame] | 400 | Michael McLay started this module. Steve Majewski changed the |
| 401 | interface to SvFormContentDict and FormContentDict. The multipart |
| 402 | parsing was inspired by code submitted by Andreas Paepcke. Guido van |
| 403 | Rossum rewrote, reformatted and documented the module and is currently |
| 404 | responsible for its maintenance. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 405 | |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 406 | |
| 407 | XXX The module is getting pretty heavy with all those docstrings. |
| 408 | Perhaps there should be a slimmed version that doesn't contain all those |
| 409 | backwards compatible and debugging classes and functions? |
| 410 | |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 411 | """ |
| 412 | |
Guido van Rossum | 9e3f429 | 1996-08-26 15:46:13 +0000 | [diff] [blame] | 413 | # " <== Emacs font-lock de-bogo-kludgificocity |
| 414 | |
Guido van Rossum | 5f32248 | 1997-04-11 18:20:42 +0000 | [diff] [blame] | 415 | __version__ = "2.2" |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 416 | |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 417 | |
| 418 | # Imports |
| 419 | # ======= |
| 420 | |
| 421 | import string |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 422 | import sys |
| 423 | import os |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 424 | |
Guido van Rossum | c204c70 | 1996-09-05 19:07:11 +0000 | [diff] [blame] | 425 | |
| 426 | # Logging support |
| 427 | # =============== |
| 428 | |
| 429 | logfile = "" # Filename to log to, if not empty |
| 430 | logfp = None # File object to log to, if not None |
| 431 | |
| 432 | def initlog(*allargs): |
| 433 | """Write a log message, if there is a log file. |
| 434 | |
| 435 | Even though this function is called initlog(), you should always |
| 436 | use log(); log is a variable that is set either to initlog |
| 437 | (initially), to dolog (once the log file has been opened), or to |
| 438 | nolog (when logging is disabled). |
| 439 | |
| 440 | The first argument is a format string; the remaining arguments (if |
| 441 | any) are arguments to the % operator, so e.g. |
| 442 | log("%s: %s", "a", "b") |
| 443 | will write "a: b" to the log file, followed by a newline. |
| 444 | |
| 445 | If the global logfp is not None, it should be a file object to |
| 446 | which log data is written. |
| 447 | |
| 448 | If the global logfp is None, the global logfile may be a string |
| 449 | giving a filename to open, in append mode. This file should be |
| 450 | world writable!!! If the file can't be opened, logging is |
| 451 | silently disabled (since there is no safe place where we could |
| 452 | send an error message). |
| 453 | |
| 454 | """ |
| 455 | global logfp, log |
| 456 | if logfile and not logfp: |
| 457 | try: |
| 458 | logfp = open(logfile, "a") |
| 459 | except IOError: |
| 460 | pass |
| 461 | if not logfp: |
| 462 | log = nolog |
| 463 | else: |
| 464 | log = dolog |
| 465 | apply(log, allargs) |
| 466 | |
| 467 | def dolog(fmt, *args): |
| 468 | """Write a log message to the log file. See initlog() for docs.""" |
| 469 | logfp.write(fmt%args + "\n") |
| 470 | |
| 471 | def nolog(*allargs): |
| 472 | """Dummy function, assigned to log when logging is disabled.""" |
| 473 | pass |
| 474 | |
| 475 | log = initlog # The current logging function |
| 476 | |
| 477 | |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 478 | # Parsing functions |
| 479 | # ================= |
| 480 | |
Guido van Rossum | e08c04c | 1996-11-11 19:29:11 +0000 | [diff] [blame] | 481 | 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] | 482 | """Parse a query in the environment or from a file (default stdin) |
| 483 | |
| 484 | Arguments, all optional: |
| 485 | |
| 486 | fp : file pointer; default: sys.stdin |
| 487 | |
| 488 | environ : environment dictionary; default: os.environ |
| 489 | |
| 490 | keep_blank_values: flag indicating whether blank values in |
| 491 | URL encoded forms should be treated as blank strings. |
| 492 | A true value inicates that blanks should be retained as |
| 493 | blank strings. The default false value indicates that |
| 494 | blank values are to be ignored and treated as if they were |
| 495 | not included. |
Guido van Rossum | e08c04c | 1996-11-11 19:29:11 +0000 | [diff] [blame] | 496 | |
| 497 | strict_parsing: flag indicating what to do with parsing errors. |
| 498 | If false (the default), errors are silently ignored. |
| 499 | If true, errors raise a ValueError exception. |
Guido van Rossum | 773ab27 | 1996-07-23 03:46:24 +0000 | [diff] [blame] | 500 | """ |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 501 | if not fp: |
| 502 | fp = sys.stdin |
| 503 | if not environ.has_key('REQUEST_METHOD'): |
| 504 | environ['REQUEST_METHOD'] = 'GET' # For testing stand-alone |
| 505 | if environ['REQUEST_METHOD'] == 'POST': |
| 506 | ctype, pdict = parse_header(environ['CONTENT_TYPE']) |
| 507 | if ctype == 'multipart/form-data': |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 508 | return parse_multipart(fp, pdict) |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 509 | elif ctype == 'application/x-www-form-urlencoded': |
| 510 | clength = string.atoi(environ['CONTENT_LENGTH']) |
| 511 | qs = fp.read(clength) |
Guido van Rossum | 1c9daa8 | 1995-09-18 21:52:37 +0000 | [diff] [blame] | 512 | else: |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 513 | qs = '' # Unknown content-type |
Guido van Rossum | afb5e93 | 1996-08-08 18:42:12 +0000 | [diff] [blame] | 514 | if environ.has_key('QUERY_STRING'): |
| 515 | if qs: qs = qs + '&' |
| 516 | qs = qs + environ['QUERY_STRING'] |
| 517 | elif sys.argv[1:]: |
| 518 | if qs: qs = qs + '&' |
| 519 | qs = qs + sys.argv[1] |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 520 | environ['QUERY_STRING'] = qs # XXX Shouldn't, really |
| 521 | elif environ.has_key('QUERY_STRING'): |
| 522 | qs = environ['QUERY_STRING'] |
| 523 | else: |
| 524 | if sys.argv[1:]: |
| 525 | qs = sys.argv[1] |
| 526 | else: |
| 527 | qs = "" |
| 528 | environ['QUERY_STRING'] = qs # XXX Shouldn't, really |
Guido van Rossum | e08c04c | 1996-11-11 19:29:11 +0000 | [diff] [blame] | 529 | return parse_qs(qs, keep_blank_values, strict_parsing) |
Guido van Rossum | e780877 | 1995-08-07 20:12:09 +0000 | [diff] [blame] | 530 | |
| 531 | |
Guido van Rossum | e08c04c | 1996-11-11 19:29:11 +0000 | [diff] [blame] | 532 | def parse_qs(qs, keep_blank_values=0, strict_parsing=0): |
| 533 | """Parse a query given as a string argument. |
Guido van Rossum | 773ab27 | 1996-07-23 03:46:24 +0000 | [diff] [blame] | 534 | |
| 535 | Arguments: |
| 536 | |
Guido van Rossum | e08c04c | 1996-11-11 19:29:11 +0000 | [diff] [blame] | 537 | qs: URL-encoded query string to be parsed |
Guido van Rossum | 773ab27 | 1996-07-23 03:46:24 +0000 | [diff] [blame] | 538 | |
| 539 | keep_blank_values: flag indicating whether blank values in |
| 540 | URL encoded queries should be treated as blank strings. |
| 541 | A true value inicates that blanks should be retained as |
| 542 | blank strings. The default false value indicates that |
| 543 | blank values are to be ignored and treated as if they were |
| 544 | not included. |
Guido van Rossum | e08c04c | 1996-11-11 19:29:11 +0000 | [diff] [blame] | 545 | |
| 546 | strict_parsing: flag indicating what to do with parsing errors. |
| 547 | If false (the default), errors are silently ignored. |
| 548 | If true, errors raise a ValueError exception. |
Guido van Rossum | 773ab27 | 1996-07-23 03:46:24 +0000 | [diff] [blame] | 549 | """ |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 550 | import urllib, regsub |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 551 | name_value_pairs = string.splitfields(qs, '&') |
| 552 | dict = {} |
| 553 | for name_value in name_value_pairs: |
| 554 | nv = string.splitfields(name_value, '=') |
| 555 | if len(nv) != 2: |
Guido van Rossum | e08c04c | 1996-11-11 19:29:11 +0000 | [diff] [blame] | 556 | if strict_parsing: |
| 557 | raise ValueError, "bad query field: %s" % `name_value` |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 558 | continue |
Guido van Rossum | 5f32248 | 1997-04-11 18:20:42 +0000 | [diff] [blame] | 559 | name = urllib.unquote(regsub.gsub('+', ' ', nv[0])) |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 560 | value = urllib.unquote(regsub.gsub('+', ' ', nv[1])) |
Guido van Rossum | 773ab27 | 1996-07-23 03:46:24 +0000 | [diff] [blame] | 561 | if len(value) or keep_blank_values: |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 562 | if dict.has_key (name): |
| 563 | dict[name].append(value) |
| 564 | else: |
| 565 | dict[name] = [value] |
| 566 | return dict |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 567 | |
| 568 | |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 569 | def parse_multipart(fp, pdict): |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 570 | """Parse multipart input. |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 571 | |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 572 | Arguments: |
| 573 | fp : input file |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 574 | pdict: dictionary containing other parameters of conten-type header |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 575 | |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 576 | Returns a dictionary just like parse_qs(): keys are the field names, each |
| 577 | value is a list of values for that field. This is easy to use but not |
| 578 | much good if you are expecting megabytes to be uploaded -- in that case, |
| 579 | use the FieldStorage class instead which is much more flexible. Note |
| 580 | that content-type is the raw, unparsed contents of the content-type |
| 581 | header. |
| 582 | |
| 583 | XXX This does not parse nested multipart parts -- use FieldStorage for |
| 584 | that. |
| 585 | |
| 586 | XXX This should really be subsumed by FieldStorage altogether -- no |
| 587 | point in having two implementations of the same parsing algorithm. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 588 | |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 589 | """ |
| 590 | import mimetools |
| 591 | if pdict.has_key('boundary'): |
| 592 | boundary = pdict['boundary'] |
| 593 | else: |
| 594 | boundary = "" |
| 595 | nextpart = "--" + boundary |
| 596 | lastpart = "--" + boundary + "--" |
| 597 | partdict = {} |
| 598 | terminator = "" |
| 599 | |
| 600 | while terminator != lastpart: |
| 601 | bytes = -1 |
| 602 | data = None |
| 603 | if terminator: |
| 604 | # At start of next part. Read headers first. |
| 605 | headers = mimetools.Message(fp) |
| 606 | clength = headers.getheader('content-length') |
| 607 | if clength: |
| 608 | try: |
| 609 | bytes = string.atoi(clength) |
| 610 | except string.atoi_error: |
| 611 | pass |
| 612 | if bytes > 0: |
| 613 | data = fp.read(bytes) |
| 614 | else: |
| 615 | data = "" |
| 616 | # Read lines until end of part. |
| 617 | lines = [] |
| 618 | while 1: |
| 619 | line = fp.readline() |
| 620 | if not line: |
| 621 | terminator = lastpart # End outer loop |
| 622 | break |
| 623 | if line[:2] == "--": |
| 624 | terminator = string.strip(line) |
| 625 | if terminator in (nextpart, lastpart): |
| 626 | break |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 627 | lines.append(line) |
| 628 | # Done with part. |
| 629 | if data is None: |
| 630 | continue |
| 631 | if bytes < 0: |
Guido van Rossum | 99aa2a4 | 1996-07-23 17:27:05 +0000 | [diff] [blame] | 632 | if lines: |
| 633 | # Strip final line terminator |
| 634 | line = lines[-1] |
| 635 | if line[-2:] == "\r\n": |
| 636 | line = line[:-2] |
| 637 | elif line[-1:] == "\n": |
| 638 | line = line[:-1] |
| 639 | lines[-1] = line |
| 640 | data = string.joinfields(lines, "") |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 641 | line = headers['content-disposition'] |
| 642 | if not line: |
| 643 | continue |
| 644 | key, params = parse_header(line) |
| 645 | if key != 'form-data': |
| 646 | continue |
| 647 | if params.has_key('name'): |
| 648 | name = params['name'] |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 649 | else: |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 650 | continue |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 651 | if partdict.has_key(name): |
| 652 | partdict[name].append(data) |
| 653 | else: |
| 654 | partdict[name] = [data] |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 655 | |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 656 | return partdict |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 657 | |
| 658 | |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 659 | def parse_header(line): |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 660 | """Parse a Content-type like header. |
| 661 | |
| 662 | Return the main content-type and a dictionary of options. |
| 663 | |
| 664 | """ |
| 665 | plist = map(string.strip, string.splitfields(line, ';')) |
| 666 | key = string.lower(plist[0]) |
| 667 | del plist[0] |
| 668 | pdict = {} |
| 669 | for p in plist: |
| 670 | i = string.find(p, '=') |
| 671 | if i >= 0: |
| 672 | name = string.lower(string.strip(p[:i])) |
| 673 | value = string.strip(p[i+1:]) |
| 674 | if len(value) >= 2 and value[0] == value[-1] == '"': |
| 675 | value = value[1:-1] |
| 676 | pdict[name] = value |
| 677 | return key, pdict |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 678 | |
| 679 | |
Guido van Rossum | 243ddcd | 1996-03-07 06:33:07 +0000 | [diff] [blame] | 680 | # Classes for field storage |
| 681 | # ========================= |
| 682 | |
| 683 | class MiniFieldStorage: |
| 684 | |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 685 | """Like FieldStorage, for use when no file uploads are possible.""" |
Guido van Rossum | 243ddcd | 1996-03-07 06:33:07 +0000 | [diff] [blame] | 686 | |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 687 | # Dummy attributes |
| 688 | filename = None |
| 689 | list = None |
| 690 | type = None |
Guido van Rossum | 773ab27 | 1996-07-23 03:46:24 +0000 | [diff] [blame] | 691 | file = None |
Guido van Rossum | 4032c2c | 1996-03-09 04:04:35 +0000 | [diff] [blame] | 692 | type_options = {} |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 693 | disposition = None |
| 694 | disposition_options = {} |
| 695 | headers = {} |
Guido van Rossum | 243ddcd | 1996-03-07 06:33:07 +0000 | [diff] [blame] | 696 | |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 697 | def __init__(self, name, value): |
| 698 | """Constructor from field name and value.""" |
| 699 | from StringIO import StringIO |
| 700 | self.name = name |
| 701 | self.value = value |
Guido van Rossum | 773ab27 | 1996-07-23 03:46:24 +0000 | [diff] [blame] | 702 | # self.file = StringIO(value) |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 703 | |
| 704 | def __repr__(self): |
| 705 | """Return printable representation.""" |
| 706 | return "MiniFieldStorage(%s, %s)" % (`self.name`, `self.value`) |
Guido van Rossum | 243ddcd | 1996-03-07 06:33:07 +0000 | [diff] [blame] | 707 | |
| 708 | |
| 709 | class FieldStorage: |
| 710 | |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 711 | """Store a sequence of fields, reading multipart/form-data. |
Guido van Rossum | 243ddcd | 1996-03-07 06:33:07 +0000 | [diff] [blame] | 712 | |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 713 | This class provides naming, typing, files stored on disk, and |
| 714 | more. At the top level, it is accessible like a dictionary, whose |
| 715 | keys are the field names. (Note: None can occur as a field name.) |
| 716 | The items are either a Python list (if there's multiple values) or |
| 717 | another FieldStorage or MiniFieldStorage object. If it's a single |
| 718 | object, it has the following attributes: |
Guido van Rossum | 243ddcd | 1996-03-07 06:33:07 +0000 | [diff] [blame] | 719 | |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 720 | name: the field name, if specified; otherwise None |
Guido van Rossum | 243ddcd | 1996-03-07 06:33:07 +0000 | [diff] [blame] | 721 | |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 722 | filename: the filename, if specified; otherwise None; this is the |
| 723 | client side filename, *not* the file name on which it is |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 724 | stored (that's a temporary file you don't deal with) |
Guido van Rossum | 243ddcd | 1996-03-07 06:33:07 +0000 | [diff] [blame] | 725 | |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 726 | value: the value as a *string*; for file uploads, this |
| 727 | transparently reads the file every time you request the value |
| 728 | |
| 729 | file: the file(-like) object from which you can read the data; |
| 730 | None if the data is stored a simple string |
| 731 | |
| 732 | type: the content-type, or None if not specified |
| 733 | |
| 734 | type_options: dictionary of options specified on the content-type |
| 735 | line |
| 736 | |
| 737 | disposition: content-disposition, or None if not specified |
| 738 | |
| 739 | disposition_options: dictionary of corresponding options |
| 740 | |
| 741 | headers: a dictionary(-like) object (sometimes rfc822.Message or a |
| 742 | subclass thereof) containing *all* headers |
| 743 | |
| 744 | The class is subclassable, mostly for the purpose of overriding |
| 745 | the make_file() method, which is called internally to come up with |
| 746 | a file open for reading and writing. This makes it possible to |
| 747 | override the default choice of storing all files in a temporary |
| 748 | directory and unlinking them as soon as they have been opened. |
| 749 | |
| 750 | """ |
| 751 | |
Guido van Rossum | 773ab27 | 1996-07-23 03:46:24 +0000 | [diff] [blame] | 752 | def __init__(self, fp=None, headers=None, outerboundary="", |
Guido van Rossum | e08c04c | 1996-11-11 19:29:11 +0000 | [diff] [blame] | 753 | environ=os.environ, keep_blank_values=0, strict_parsing=0): |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 754 | """Constructor. Read multipart/* until last part. |
| 755 | |
| 756 | Arguments, all optional: |
| 757 | |
| 758 | fp : file pointer; default: sys.stdin |
| 759 | |
| 760 | headers : header dictionary-like object; default: |
| 761 | taken from environ as per CGI spec |
| 762 | |
Guido van Rossum | 773ab27 | 1996-07-23 03:46:24 +0000 | [diff] [blame] | 763 | outerboundary : terminating multipart boundary |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 764 | (for internal use only) |
| 765 | |
Guido van Rossum | 773ab27 | 1996-07-23 03:46:24 +0000 | [diff] [blame] | 766 | environ : environment dictionary; default: os.environ |
| 767 | |
| 768 | keep_blank_values: flag indicating whether blank values in |
| 769 | URL encoded forms should be treated as blank strings. |
| 770 | A true value inicates that blanks should be retained as |
| 771 | blank strings. The default false value indicates that |
| 772 | blank values are to be ignored and treated as if they were |
| 773 | not included. |
| 774 | |
Guido van Rossum | e08c04c | 1996-11-11 19:29:11 +0000 | [diff] [blame] | 775 | strict_parsing: flag indicating what to do with parsing errors. |
| 776 | If false (the default), errors are silently ignored. |
| 777 | If true, errors raise a ValueError exception. |
| 778 | |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 779 | """ |
| 780 | method = None |
Guido van Rossum | 773ab27 | 1996-07-23 03:46:24 +0000 | [diff] [blame] | 781 | self.keep_blank_values = keep_blank_values |
Guido van Rossum | e08c04c | 1996-11-11 19:29:11 +0000 | [diff] [blame] | 782 | self.strict_parsing = strict_parsing |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 783 | if environ.has_key('REQUEST_METHOD'): |
| 784 | method = string.upper(environ['REQUEST_METHOD']) |
| 785 | if not fp and method == 'GET': |
| 786 | qs = None |
| 787 | if environ.has_key('QUERY_STRING'): |
| 788 | qs = environ['QUERY_STRING'] |
| 789 | from StringIO import StringIO |
| 790 | fp = StringIO(qs or "") |
| 791 | if headers is None: |
| 792 | headers = {'content-type': |
| 793 | "application/x-www-form-urlencoded"} |
| 794 | if headers is None: |
| 795 | headers = {} |
| 796 | if environ.has_key('CONTENT_TYPE'): |
| 797 | headers['content-type'] = environ['CONTENT_TYPE'] |
| 798 | if environ.has_key('CONTENT_LENGTH'): |
| 799 | headers['content-length'] = environ['CONTENT_LENGTH'] |
| 800 | self.fp = fp or sys.stdin |
| 801 | self.headers = headers |
| 802 | self.outerboundary = outerboundary |
| 803 | |
| 804 | # Process content-disposition header |
| 805 | cdisp, pdict = "", {} |
| 806 | if self.headers.has_key('content-disposition'): |
| 807 | cdisp, pdict = parse_header(self.headers['content-disposition']) |
| 808 | self.disposition = cdisp |
| 809 | self.disposition_options = pdict |
| 810 | self.name = None |
| 811 | if pdict.has_key('name'): |
| 812 | self.name = pdict['name'] |
| 813 | self.filename = None |
| 814 | if pdict.has_key('filename'): |
| 815 | self.filename = pdict['filename'] |
| 816 | |
| 817 | # Process content-type header |
| 818 | ctype, pdict = "text/plain", {} |
| 819 | if self.headers.has_key('content-type'): |
| 820 | ctype, pdict = parse_header(self.headers['content-type']) |
| 821 | self.type = ctype |
| 822 | self.type_options = pdict |
| 823 | self.innerboundary = "" |
| 824 | if pdict.has_key('boundary'): |
| 825 | self.innerboundary = pdict['boundary'] |
| 826 | clen = -1 |
| 827 | if self.headers.has_key('content-length'): |
| 828 | try: |
| 829 | clen = string.atoi(self.headers['content-length']) |
| 830 | except: |
| 831 | pass |
| 832 | self.length = clen |
| 833 | |
| 834 | self.list = self.file = None |
| 835 | self.done = 0 |
| 836 | self.lines = [] |
| 837 | if ctype == 'application/x-www-form-urlencoded': |
| 838 | self.read_urlencoded() |
| 839 | elif ctype[:10] == 'multipart/': |
| 840 | self.read_multi() |
| 841 | else: |
| 842 | self.read_single() |
| 843 | |
| 844 | def __repr__(self): |
| 845 | """Return a printable representation.""" |
| 846 | return "FieldStorage(%s, %s, %s)" % ( |
| 847 | `self.name`, `self.filename`, `self.value`) |
| 848 | |
| 849 | def __getattr__(self, name): |
| 850 | if name != 'value': |
| 851 | raise AttributeError, name |
| 852 | if self.file: |
| 853 | self.file.seek(0) |
| 854 | value = self.file.read() |
| 855 | self.file.seek(0) |
| 856 | elif self.list is not None: |
| 857 | value = self.list |
| 858 | else: |
| 859 | value = None |
| 860 | return value |
| 861 | |
| 862 | def __getitem__(self, key): |
| 863 | """Dictionary style indexing.""" |
| 864 | if self.list is None: |
| 865 | raise TypeError, "not indexable" |
| 866 | found = [] |
| 867 | for item in self.list: |
| 868 | if item.name == key: found.append(item) |
| 869 | if not found: |
| 870 | raise KeyError, key |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 871 | if len(found) == 1: |
| 872 | return found[0] |
| 873 | else: |
| 874 | return found |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 875 | |
| 876 | def keys(self): |
| 877 | """Dictionary style keys() method.""" |
| 878 | if self.list is None: |
| 879 | raise TypeError, "not indexable" |
| 880 | keys = [] |
| 881 | for item in self.list: |
| 882 | if item.name not in keys: keys.append(item.name) |
| 883 | return keys |
| 884 | |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 885 | def has_key(self, key): |
| 886 | """Dictionary style has_key() method.""" |
| 887 | if self.list is None: |
| 888 | raise TypeError, "not indexable" |
| 889 | for item in self.list: |
| 890 | if item.name == key: return 1 |
| 891 | return 0 |
| 892 | |
Guido van Rossum | 88b85d4 | 1997-01-11 19:21:33 +0000 | [diff] [blame] | 893 | def __len__(self): |
| 894 | """Dictionary style len(x) support.""" |
| 895 | return len(self.keys()) |
| 896 | |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 897 | def read_urlencoded(self): |
| 898 | """Internal: read data in query string format.""" |
| 899 | qs = self.fp.read(self.length) |
Guido van Rossum | e08c04c | 1996-11-11 19:29:11 +0000 | [diff] [blame] | 900 | dict = parse_qs(qs, self.keep_blank_values, self.strict_parsing) |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 901 | self.list = [] |
| 902 | for key, valuelist in dict.items(): |
| 903 | for value in valuelist: |
| 904 | self.list.append(MiniFieldStorage(key, value)) |
| 905 | self.skip_lines() |
| 906 | |
| 907 | def read_multi(self): |
| 908 | """Internal: read a part that is itself multipart.""" |
| 909 | import rfc822 |
| 910 | self.list = [] |
| 911 | part = self.__class__(self.fp, {}, self.innerboundary) |
| 912 | # Throw first part away |
| 913 | while not part.done: |
| 914 | headers = rfc822.Message(self.fp) |
| 915 | part = self.__class__(self.fp, headers, self.innerboundary) |
| 916 | self.list.append(part) |
| 917 | self.skip_lines() |
| 918 | |
| 919 | def read_single(self): |
| 920 | """Internal: read an atomic part.""" |
| 921 | if self.length >= 0: |
| 922 | self.read_binary() |
| 923 | self.skip_lines() |
| 924 | else: |
| 925 | self.read_lines() |
| 926 | self.file.seek(0) |
| 927 | |
| 928 | bufsize = 8*1024 # I/O buffering size for copy to file |
| 929 | |
| 930 | def read_binary(self): |
| 931 | """Internal: read binary data.""" |
| 932 | self.file = self.make_file('b') |
| 933 | todo = self.length |
| 934 | if todo >= 0: |
| 935 | while todo > 0: |
| 936 | data = self.fp.read(min(todo, self.bufsize)) |
| 937 | if not data: |
| 938 | self.done = -1 |
| 939 | break |
| 940 | self.file.write(data) |
| 941 | todo = todo - len(data) |
| 942 | |
| 943 | def read_lines(self): |
| 944 | """Internal: read lines until EOF or outerboundary.""" |
| 945 | self.file = self.make_file('') |
| 946 | if self.outerboundary: |
| 947 | self.read_lines_to_outerboundary() |
| 948 | else: |
| 949 | self.read_lines_to_eof() |
| 950 | |
| 951 | def read_lines_to_eof(self): |
| 952 | """Internal: read lines until EOF.""" |
| 953 | while 1: |
| 954 | line = self.fp.readline() |
| 955 | if not line: |
| 956 | self.done = -1 |
| 957 | break |
| 958 | self.lines.append(line) |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 959 | self.file.write(line) |
| 960 | |
| 961 | def read_lines_to_outerboundary(self): |
| 962 | """Internal: read lines until outerboundary.""" |
| 963 | next = "--" + self.outerboundary |
| 964 | last = next + "--" |
| 965 | delim = "" |
| 966 | while 1: |
| 967 | line = self.fp.readline() |
| 968 | if not line: |
| 969 | self.done = -1 |
| 970 | break |
| 971 | self.lines.append(line) |
| 972 | if line[:2] == "--": |
| 973 | strippedline = string.strip(line) |
| 974 | if strippedline == next: |
| 975 | break |
| 976 | if strippedline == last: |
| 977 | self.done = 1 |
| 978 | break |
Guido van Rossum | e5e46e0 | 1996-09-05 19:03:36 +0000 | [diff] [blame] | 979 | odelim = delim |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 980 | if line[-2:] == "\r\n": |
Guido van Rossum | 99aa2a4 | 1996-07-23 17:27:05 +0000 | [diff] [blame] | 981 | delim = "\r\n" |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 982 | line = line[:-2] |
| 983 | elif line[-1] == "\n": |
Guido van Rossum | 99aa2a4 | 1996-07-23 17:27:05 +0000 | [diff] [blame] | 984 | delim = "\n" |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 985 | line = line[:-1] |
Guido van Rossum | 99aa2a4 | 1996-07-23 17:27:05 +0000 | [diff] [blame] | 986 | else: |
| 987 | delim = "" |
Guido van Rossum | e5e46e0 | 1996-09-05 19:03:36 +0000 | [diff] [blame] | 988 | self.file.write(odelim + line) |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 989 | |
| 990 | def skip_lines(self): |
| 991 | """Internal: skip lines until outer boundary if defined.""" |
| 992 | if not self.outerboundary or self.done: |
| 993 | return |
| 994 | next = "--" + self.outerboundary |
| 995 | last = next + "--" |
| 996 | while 1: |
| 997 | line = self.fp.readline() |
| 998 | if not line: |
| 999 | self.done = -1 |
| 1000 | break |
| 1001 | self.lines.append(line) |
| 1002 | if line[:2] == "--": |
| 1003 | strippedline = string.strip(line) |
| 1004 | if strippedline == next: |
| 1005 | break |
| 1006 | if strippedline == last: |
| 1007 | self.done = 1 |
| 1008 | break |
| 1009 | |
| 1010 | def make_file(self, binary): |
| 1011 | """Overridable: return a readable & writable file. |
| 1012 | |
| 1013 | The file will be used as follows: |
| 1014 | - data is written to it |
| 1015 | - seek(0) |
| 1016 | - data is read from it |
| 1017 | |
| 1018 | The 'binary' argument is 'b' if the file should be created in |
| 1019 | binary mode (on non-Unix systems), '' otherwise. |
| 1020 | |
Guido van Rossum | 4032c2c | 1996-03-09 04:04:35 +0000 | [diff] [blame] | 1021 | This version opens a temporary file for reading and writing, |
| 1022 | and immediately deletes (unlinks) it. The trick (on Unix!) is |
| 1023 | that the file can still be used, but it can't be opened by |
| 1024 | another process, and it will automatically be deleted when it |
| 1025 | is closed or when the current process terminates. |
| 1026 | |
| 1027 | If you want a more permanent file, you derive a class which |
| 1028 | overrides this method. If you want a visible temporary file |
| 1029 | that is nevertheless automatically deleted when the script |
| 1030 | terminates, try defining a __del__ method in a derived class |
| 1031 | which unlinks the temporary files you have created. |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1032 | |
| 1033 | """ |
Guido van Rossum | 4032c2c | 1996-03-09 04:04:35 +0000 | [diff] [blame] | 1034 | import tempfile |
| 1035 | tfn = tempfile.mktemp() |
| 1036 | f = open(tfn, "w%s+" % binary) |
| 1037 | os.unlink(tfn) |
| 1038 | return f |
Guido van Rossum | 243ddcd | 1996-03-07 06:33:07 +0000 | [diff] [blame] | 1039 | |
| 1040 | |
Guido van Rossum | 4032c2c | 1996-03-09 04:04:35 +0000 | [diff] [blame] | 1041 | # Backwards Compatibility Classes |
| 1042 | # =============================== |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1043 | |
| 1044 | class FormContentDict: |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1045 | """Basic (multiple values per field) form content as dictionary. |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 1046 | |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1047 | form = FormContentDict() |
| 1048 | |
| 1049 | form[key] -> [value, value, ...] |
| 1050 | form.has_key(key) -> Boolean |
| 1051 | form.keys() -> [key, key, ...] |
| 1052 | form.values() -> [[val, val, ...], [val, val, ...], ...] |
| 1053 | form.items() -> [(key, [val, val, ...]), (key, [val, val, ...]), ...] |
| 1054 | form.dict == {key: [val, val, ...], ...} |
| 1055 | |
| 1056 | """ |
Guido van Rossum | 773ab27 | 1996-07-23 03:46:24 +0000 | [diff] [blame] | 1057 | def __init__(self, environ=os.environ): |
Guido van Rossum | afb5e93 | 1996-08-08 18:42:12 +0000 | [diff] [blame] | 1058 | self.dict = parse(environ=environ) |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1059 | self.query_string = environ['QUERY_STRING'] |
| 1060 | def __getitem__(self,key): |
| 1061 | return self.dict[key] |
| 1062 | def keys(self): |
| 1063 | return self.dict.keys() |
| 1064 | def has_key(self, key): |
| 1065 | return self.dict.has_key(key) |
| 1066 | def values(self): |
| 1067 | return self.dict.values() |
| 1068 | def items(self): |
| 1069 | return self.dict.items() |
| 1070 | def __len__( self ): |
| 1071 | return len(self.dict) |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1072 | |
| 1073 | |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1074 | class SvFormContentDict(FormContentDict): |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1075 | """Strict single-value expecting form content as dictionary. |
| 1076 | |
| 1077 | IF you only expect a single value for each field, then form[key] |
| 1078 | will return that single value. It will raise an IndexError if |
| 1079 | that expectation is not true. IF you expect a field to have |
| 1080 | possible multiple values, than you can use form.getlist(key) to |
| 1081 | get all of the values. values() and items() are a compromise: |
| 1082 | they return single strings where there is a single value, and |
| 1083 | lists of strings otherwise. |
| 1084 | |
| 1085 | """ |
| 1086 | def __getitem__(self, key): |
| 1087 | if len(self.dict[key]) > 1: |
| 1088 | raise IndexError, 'expecting a single value' |
| 1089 | return self.dict[key][0] |
| 1090 | def getlist(self, key): |
| 1091 | return self.dict[key] |
| 1092 | def values(self): |
| 1093 | lis = [] |
| 1094 | for each in self.dict.values(): |
| 1095 | if len( each ) == 1 : |
| 1096 | lis.append(each[0]) |
| 1097 | else: lis.append(each) |
| 1098 | return lis |
| 1099 | def items(self): |
| 1100 | lis = [] |
| 1101 | for key,value in self.dict.items(): |
| 1102 | if len(value) == 1 : |
| 1103 | lis.append((key, value[0])) |
| 1104 | else: lis.append((key, value)) |
| 1105 | return lis |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1106 | |
| 1107 | |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1108 | class InterpFormContentDict(SvFormContentDict): |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1109 | """This class is present for backwards compatibility only.""" |
| 1110 | def __getitem__( self, key ): |
| 1111 | v = SvFormContentDict.__getitem__( self, key ) |
| 1112 | if v[0] in string.digits+'+-.' : |
| 1113 | try: return string.atoi( v ) |
| 1114 | except ValueError: |
| 1115 | try: return string.atof( v ) |
| 1116 | except ValueError: pass |
| 1117 | return string.strip(v) |
| 1118 | def values( self ): |
| 1119 | lis = [] |
| 1120 | for key in self.keys(): |
| 1121 | try: |
| 1122 | lis.append( self[key] ) |
| 1123 | except IndexError: |
| 1124 | lis.append( self.dict[key] ) |
| 1125 | return lis |
| 1126 | def items( self ): |
| 1127 | lis = [] |
| 1128 | for key in self.keys(): |
| 1129 | try: |
| 1130 | lis.append( (key, self[key]) ) |
| 1131 | except IndexError: |
| 1132 | lis.append( (key, self.dict[key]) ) |
| 1133 | return lis |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1134 | |
| 1135 | |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1136 | class FormContent(FormContentDict): |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1137 | """This class is present for backwards compatibility only.""" |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 1138 | def values(self, key): |
| 1139 | if self.dict.has_key(key) :return self.dict[key] |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1140 | else: return None |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 1141 | def indexed_value(self, key, location): |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1142 | if self.dict.has_key(key): |
| 1143 | if len (self.dict[key]) > location: |
| 1144 | return self.dict[key][location] |
| 1145 | else: return None |
| 1146 | else: return None |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 1147 | def value(self, key): |
| 1148 | if self.dict.has_key(key): return self.dict[key][0] |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1149 | else: return None |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 1150 | def length(self, key): |
| 1151 | return len(self.dict[key]) |
| 1152 | def stripped(self, key): |
| 1153 | if self.dict.has_key(key): return string.strip(self.dict[key][0]) |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1154 | else: return None |
| 1155 | def pars(self): |
| 1156 | return self.dict |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1157 | |
| 1158 | |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 1159 | # Test/debug code |
| 1160 | # =============== |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1161 | |
Guido van Rossum | 773ab27 | 1996-07-23 03:46:24 +0000 | [diff] [blame] | 1162 | def test(environ=os.environ): |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1163 | """Robust test CGI script, usable as main program. |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1164 | |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1165 | Write minimal HTTP headers and dump all information provided to |
| 1166 | the script in HTML form. |
| 1167 | |
| 1168 | """ |
| 1169 | import traceback |
| 1170 | print "Content-type: text/html" |
| 1171 | print |
| 1172 | sys.stderr = sys.stdout |
| 1173 | try: |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 1174 | form = FieldStorage() # Replace with other classes to test those |
| 1175 | print_form(form) |
Guido van Rossum | 773ab27 | 1996-07-23 03:46:24 +0000 | [diff] [blame] | 1176 | print_environ(environ) |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1177 | print_directory() |
Guido van Rossum | a8738a5 | 1996-03-14 21:30:28 +0000 | [diff] [blame] | 1178 | print_arguments() |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1179 | print_environ_usage() |
Guido van Rossum | f85de8a | 1996-08-20 20:22:39 +0000 | [diff] [blame] | 1180 | def f(): |
| 1181 | exec "testing print_exception() -- <I>italics?</I>" |
| 1182 | def g(f=f): |
| 1183 | f() |
| 1184 | print "<H3>What follows is a test, not an actual exception:</H3>" |
| 1185 | g() |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1186 | except: |
Guido van Rossum | f85de8a | 1996-08-20 20:22:39 +0000 | [diff] [blame] | 1187 | print_exception() |
| 1188 | |
| 1189 | def print_exception(type=None, value=None, tb=None, limit=None): |
| 1190 | if type is None: |
| 1191 | type, value, tb = sys.exc_type, sys.exc_value, sys.exc_traceback |
| 1192 | import traceback |
| 1193 | print |
| 1194 | print "<H3>Traceback (innermost last):</H3>" |
| 1195 | list = traceback.format_tb(tb, limit) + \ |
| 1196 | traceback.format_exception_only(type, value) |
| 1197 | print "<PRE>%s<B>%s</B></PRE>" % ( |
| 1198 | escape(string.join(list[:-1], "")), |
| 1199 | escape(list[-1]), |
| 1200 | ) |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1201 | |
Guido van Rossum | 773ab27 | 1996-07-23 03:46:24 +0000 | [diff] [blame] | 1202 | def print_environ(environ=os.environ): |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1203 | """Dump the shell environment as HTML.""" |
| 1204 | keys = environ.keys() |
| 1205 | keys.sort() |
| 1206 | print |
Guido van Rossum | 503e50b | 1996-05-28 22:57:20 +0000 | [diff] [blame] | 1207 | print "<H3>Shell Environment:</H3>" |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1208 | print "<DL>" |
| 1209 | for key in keys: |
| 1210 | print "<DT>", escape(key), "<DD>", escape(environ[key]) |
| 1211 | print "</DL>" |
| 1212 | print |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 1213 | |
| 1214 | def print_form(form): |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1215 | """Dump the contents of a form as HTML.""" |
| 1216 | keys = form.keys() |
| 1217 | keys.sort() |
| 1218 | print |
Guido van Rossum | 503e50b | 1996-05-28 22:57:20 +0000 | [diff] [blame] | 1219 | print "<H3>Form Contents:</H3>" |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1220 | print "<DL>" |
| 1221 | for key in keys: |
| 1222 | print "<DT>" + escape(key) + ":", |
| 1223 | value = form[key] |
| 1224 | print "<i>" + escape(`type(value)`) + "</i>" |
| 1225 | print "<DD>" + escape(`value`) |
| 1226 | print "</DL>" |
| 1227 | print |
| 1228 | |
| 1229 | def print_directory(): |
| 1230 | """Dump the current directory as HTML.""" |
| 1231 | print |
| 1232 | print "<H3>Current Working Directory:</H3>" |
| 1233 | try: |
| 1234 | pwd = os.getcwd() |
| 1235 | except os.error, msg: |
| 1236 | print "os.error:", escape(str(msg)) |
| 1237 | else: |
| 1238 | print escape(pwd) |
| 1239 | print |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1240 | |
Guido van Rossum | a8738a5 | 1996-03-14 21:30:28 +0000 | [diff] [blame] | 1241 | def print_arguments(): |
| 1242 | print |
Guido van Rossum | 503e50b | 1996-05-28 22:57:20 +0000 | [diff] [blame] | 1243 | print "<H3>Command Line Arguments:</H3>" |
Guido van Rossum | a8738a5 | 1996-03-14 21:30:28 +0000 | [diff] [blame] | 1244 | print |
| 1245 | print sys.argv |
| 1246 | print |
| 1247 | |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1248 | def print_environ_usage(): |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1249 | """Dump a list of environment variables used by CGI as HTML.""" |
| 1250 | print """ |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 1251 | <H3>These environment variables could have been set:</H3> |
| 1252 | <UL> |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1253 | <LI>AUTH_TYPE |
| 1254 | <LI>CONTENT_LENGTH |
| 1255 | <LI>CONTENT_TYPE |
| 1256 | <LI>DATE_GMT |
| 1257 | <LI>DATE_LOCAL |
| 1258 | <LI>DOCUMENT_NAME |
| 1259 | <LI>DOCUMENT_ROOT |
| 1260 | <LI>DOCUMENT_URI |
| 1261 | <LI>GATEWAY_INTERFACE |
| 1262 | <LI>LAST_MODIFIED |
| 1263 | <LI>PATH |
| 1264 | <LI>PATH_INFO |
| 1265 | <LI>PATH_TRANSLATED |
| 1266 | <LI>QUERY_STRING |
| 1267 | <LI>REMOTE_ADDR |
| 1268 | <LI>REMOTE_HOST |
| 1269 | <LI>REMOTE_IDENT |
| 1270 | <LI>REMOTE_USER |
| 1271 | <LI>REQUEST_METHOD |
| 1272 | <LI>SCRIPT_NAME |
| 1273 | <LI>SERVER_NAME |
| 1274 | <LI>SERVER_PORT |
| 1275 | <LI>SERVER_PROTOCOL |
| 1276 | <LI>SERVER_ROOT |
| 1277 | <LI>SERVER_SOFTWARE |
| 1278 | </UL> |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1279 | In addition, HTTP headers sent by the server may be passed in the |
| 1280 | environment as well. Here are some common variable names: |
| 1281 | <UL> |
| 1282 | <LI>HTTP_ACCEPT |
| 1283 | <LI>HTTP_CONNECTION |
| 1284 | <LI>HTTP_HOST |
| 1285 | <LI>HTTP_PRAGMA |
| 1286 | <LI>HTTP_REFERER |
| 1287 | <LI>HTTP_USER_AGENT |
| 1288 | </UL> |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1289 | """ |
| 1290 | |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1291 | |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 1292 | # Utilities |
| 1293 | # ========= |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1294 | |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 1295 | def escape(s): |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1296 | """Replace special characters '&', '<' and '>' by SGML entities.""" |
Guido van Rossum | 0147db0 | 1996-03-09 03:16:04 +0000 | [diff] [blame] | 1297 | import regsub |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1298 | s = regsub.gsub("&", "&", s) # Must be done first! |
| 1299 | s = regsub.gsub("<", "<", s) |
| 1300 | s = regsub.gsub(">", ">", s) |
| 1301 | return s |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1302 | |
Guido van Rossum | 9a22de1 | 1995-01-12 12:29:47 +0000 | [diff] [blame] | 1303 | |
Guido van Rossum | 7275561 | 1996-03-06 07:20:06 +0000 | [diff] [blame] | 1304 | # Invoke mainline |
| 1305 | # =============== |
| 1306 | |
| 1307 | # Call test() when this file is run as a script (not imported as a module) |
| 1308 | if __name__ == '__main__': |
Guido van Rossum | 7aee384 | 1996-03-07 18:00:44 +0000 | [diff] [blame] | 1309 | test() |