blob: 15af21742cd7e21574e54c3adf504e66d87d903d [file] [log] [blame]
Guido van Rossum9a22de11995-01-12 12:29:47 +00001#!/usr/local/bin/python
Guido van Rossum1c9daa81995-09-18 21:52:37 +00002
Guido van Rossum72755611996-03-06 07:20:06 +00003"""Support module for CGI (Common Gateway Interface) scripts.
Guido van Rossum1c9daa81995-09-18 21:52:37 +00004
Guido van Rossum7aee3841996-03-07 18:00:44 +00005This module defines a number of utilities for use by CGI scripts
6written in Python.
Guido van Rossum9a22de11995-01-12 12:29:47 +00007
8
Guido van Rossum72755611996-03-06 07:20:06 +00009Introduction
10------------
11
Guido van Rossum391b4e61996-03-06 19:11:33 +000012A CGI script is invoked by an HTTP server, usually to process user
13input submitted through an HTML <FORM> or <ISINPUT> element.
Guido van Rossum72755611996-03-06 07:20:06 +000014
Guido van Rossum391b4e61996-03-06 19:11:33 +000015Most often, CGI scripts live in the server's special cgi-bin
16directory. The HTTP server places all sorts of information about the
17request (such as the client's hostname, the requested URL, the query
18string, and lots of other goodies) in the script's shell environment,
19executes the script, and sends the script's output back to the client.
Guido van Rossum72755611996-03-06 07:20:06 +000020
Guido van Rossum391b4e61996-03-06 19:11:33 +000021The script's input is connected to the client too, and sometimes the
22form data is read this way; at other times the form data is passed via
23the "query string" part of the URL. This module (cgi.py) is intended
24to take care of the different cases and provide a simpler interface to
25the Python script. It also provides a number of utilities that help
26in debugging scripts, and the latest addition is support for file
27uploads from a form (if your browser supports it -- Grail 0.3 and
28Netscape 2.0 do).
Guido van Rossum72755611996-03-06 07:20:06 +000029
Guido van Rossum391b4e61996-03-06 19:11:33 +000030The output of a CGI script should consist of two sections, separated
31by a blank line. The first section contains a number of headers,
32telling the client what kind of data is following. Python code to
33generate a minimal header section looks like this:
Guido van Rossum72755611996-03-06 07:20:06 +000034
Guido van Rossum243ddcd1996-03-07 06:33:07 +000035 print "Content-type: text/html" # HTML is following
36 print # blank line, end of headers
Guido van Rossum72755611996-03-06 07:20:06 +000037
Guido van Rossum391b4e61996-03-06 19:11:33 +000038The second section is usually HTML, which allows the client software
39to display nicely formatted text with header, in-line images, etc.
40Here's Python code that prints a simple piece of HTML:
Guido van Rossum72755611996-03-06 07:20:06 +000041
42 print "<TITLE>CGI script output</TITLE>"
43 print "<H1>This is my first CGI script</H1>"
44 print "Hello, world!"
45
Guido van Rossum391b4e61996-03-06 19:11:33 +000046(It may not be fully legal HTML according to the letter of the
47standard, but any browser will understand it.)
Guido van Rossum72755611996-03-06 07:20:06 +000048
49
50Using the cgi module
51--------------------
52
Guido van Rossum391b4e61996-03-06 19:11:33 +000053Begin by writing "import cgi". Don't use "from cgi import *" -- the
Guido van Rossum0147db01996-03-09 03:16:04 +000054module defines all sorts of names for its own use or for backward
55compatibility that you don't want in your namespace.
Guido van Rossum72755611996-03-06 07:20:06 +000056
Guido van Rossum0147db01996-03-09 03:16:04 +000057It's best to use the FieldStorage class. The other classes define in this
58module are provided mostly for backward compatibility. Instantiate it
59exactly once, without arguments. This reads the form contents from
60standard input or the environment (depending on the value of various
61environment variables set according to the CGI standard). Since it may
62consume standard input, it should be instantiated only once.
Guido van Rossum72755611996-03-06 07:20:06 +000063
Guido van Rossum0147db01996-03-09 03:16:04 +000064The FieldStorage instance can be accessed as if it were a Python
65dictionary. For instance, the following code (which assumes that the
66Content-type header and blank line have already been printed) checks that
67the fields "name" and "addr" are both set to a non-empty string:
Guido van Rossum72755611996-03-06 07:20:06 +000068
Guido van Rossum503e50b1996-05-28 22:57:20 +000069 form = cgi.FieldStorage()
Guido van Rossum72755611996-03-06 07:20:06 +000070 form_ok = 0
71 if form.has_key("name") and form.has_key("addr"):
Guido van Rossum0147db01996-03-09 03:16:04 +000072 if form["name"].value != "" and form["addr"].value != "":
Guido van Rossum72755611996-03-06 07:20:06 +000073 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 Rossum0147db01996-03-09 03:16:04 +000078 ...further form processing here...
Guido van Rossum72755611996-03-06 07:20:06 +000079
Guido van Rossum4032c2c1996-03-09 04:04:35 +000080Here the fields, accessed through form[key], are themselves instances
81of FieldStorage (or MiniFieldStorage, depending on the form encoding).
Guido van Rossum72755611996-03-06 07:20:06 +000082
Guido van Rossum4032c2c1996-03-09 04:04:35 +000083If the submitted form data contains more than one field with the same
84name, the object retrieved by form[key] is not a (Mini)FieldStorage
85instance but a list of such instances. If you expect this possibility
86(i.e., when your HTML form comtains multiple fields with the same
87name), use the type() function to determine whether you have a single
88instance or a list of instances. For example, here's code that
89concatenates any number of username fields, separated by commas:
90
91 username = form["username"]
Guido van Rossum0147db01996-03-09 03:16:04 +000092 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 Rossum4032c2c1996-03-09 04:04:35 +0000104 usernames = username.value
Guido van Rossum0147db01996-03-09 03:16:04 +0000105
106If a field represents an uploaded file, the value attribute reads the
107entire file in memory as a string. This may not be what you want. You can
108test for an uploaded file by testing either the filename attribute or the
109file attribute. You can then read the data at leasure from the file
110attribute:
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 Rossum4032c2c1996-03-09 04:04:35 +0000121The file upload draft standard entertains the possibility of uploading
122multiple files from one field (using a recursive multipart/*
123encoding). When this occurs, the item will be a dictionary-like
124FieldStorage item. This can be determined by testing its type
125attribute, which should have the value "multipart/form-data" (or
126perhaps another string beginning with "multipart/"). It this case, it
127can be iterated over recursively just like the top-level form object.
128
Guido van Rossum0147db01996-03-09 03:16:04 +0000129When a form is submitted in the "old" format (as the query string or as a
130single data part of type application/x-www-form-urlencoded), the items
131will actually be instances of the class MiniFieldStorage. In this case,
132the list, file and filename attributes are always None.
Guido van Rossum7aee3841996-03-07 18:00:44 +0000133
Guido van Rossum72755611996-03-06 07:20:06 +0000134
Guido van Rossum0147db01996-03-09 03:16:04 +0000135Old classes
136-----------
Guido van Rossum72755611996-03-06 07:20:06 +0000137
Guido van Rossum0147db01996-03-09 03:16:04 +0000138These classes, present in earlier versions of the cgi module, are still
139supported for backward compatibility. New applications should use the
Guido van Rossum7aee3841996-03-07 18:00:44 +0000140
Guido van Rossum0147db01996-03-09 03:16:04 +0000141SvFormContentDict: single value form content as dictionary; assumes each
142field name occurs in the form only once.
Guido van Rossum72755611996-03-06 07:20:06 +0000143
Guido van Rossum391b4e61996-03-06 19:11:33 +0000144FormContentDict: multiple value form content as dictionary (the form
145items are lists of values). Useful if your form contains multiple
146fields with the same name.
Guido van Rossum72755611996-03-06 07:20:06 +0000147
Guido van Rossum391b4e61996-03-06 19:11:33 +0000148Other classes (FormContent, InterpFormContentDict) are present for
Guido van Rossum0147db01996-03-09 03:16:04 +0000149backwards compatibility with really old applications only. If you still
150use these and would be inconvenienced when they disappeared from a next
151version of this module, drop me a note.
Guido van Rossum72755611996-03-06 07:20:06 +0000152
153
Guido van Rossum0147db01996-03-09 03:16:04 +0000154Functions
155---------
Guido van Rossum72755611996-03-06 07:20:06 +0000156
Guido van Rossum391b4e61996-03-06 19:11:33 +0000157These are useful if you want more control, or if you want to employ
158some of the algorithms implemented in this module in other
159circumstances.
Guido van Rossum72755611996-03-06 07:20:06 +0000160
Guido van Rossum0147db01996-03-09 03:16:04 +0000161parse(fp): parse a form into a Python dictionary.
Guido van Rossum72755611996-03-06 07:20:06 +0000162
Guido van Rossum0147db01996-03-09 03:16:04 +0000163parse_qs(qs): parse a query string (data of type
164application/x-www-form-urlencoded).
Guido van Rossum72755611996-03-06 07:20:06 +0000165
Guido van Rossum0147db01996-03-09 03:16:04 +0000166parse_multipart(fp, pdict): parse input of type multipart/form-data (for
Guido van Rossum391b4e61996-03-06 19:11:33 +0000167file uploads).
Guido van Rossum72755611996-03-06 07:20:06 +0000168
Guido van Rossum391b4e61996-03-06 19:11:33 +0000169parse_header(string): parse a header like Content-type into a main
170value and a dictionary of parameters.
Guido van Rossum72755611996-03-06 07:20:06 +0000171
172test(): complete test program.
173
174print_environ(): format the shell environment in HTML.
175
176print_form(form): format a form in HTML.
177
Guido van Rossum391b4e61996-03-06 19:11:33 +0000178print_environ_usage(): print a list of useful environment variables in
179HTML.
Guido van Rossum72755611996-03-06 07:20:06 +0000180
Guido van Rossum391b4e61996-03-06 19:11:33 +0000181escape(): convert the characters "&", "<" and ">" to HTML-safe
182sequences. Use this if you need to display text that might contain
183such characters in HTML. To translate URLs for inclusion in the HREF
184attribute of an <A> tag, use urllib.quote().
Guido van Rossum72755611996-03-06 07:20:06 +0000185
186
187Caring about security
188---------------------
189
Guido van Rossum391b4e61996-03-06 19:11:33 +0000190There's one important rule: if you invoke an external program (e.g.
191via the os.system() or os.popen() functions), make very sure you don't
192pass arbitrary strings received from the client to the shell. This is
193a well-known security hole whereby clever hackers anywhere on the web
194can exploit a gullible CGI script to invoke arbitrary shell commands.
195Even parts of the URL or field names cannot be trusted, since the
196request doesn't have to come from your form!
Guido van Rossum72755611996-03-06 07:20:06 +0000197
Guido van Rossum391b4e61996-03-06 19:11:33 +0000198To be on the safe side, if you must pass a string gotten from a form
199to a shell command, you should make sure the string contains only
200alphanumeric characters, dashes, underscores, and periods.
Guido van Rossum72755611996-03-06 07:20:06 +0000201
202
203Installing your CGI script on a Unix system
204-------------------------------------------
205
Guido van Rossum391b4e61996-03-06 19:11:33 +0000206Read the documentation for your HTTP server and check with your local
207system administrator to find the directory where CGI scripts should be
Guido van Rossum72755611996-03-06 07:20:06 +0000208installed; usually this is in a directory cgi-bin in the server tree.
209
Guido van Rossum391b4e61996-03-06 19:11:33 +0000210Make sure that your script is readable and executable by "others"; the
211Unix file mode should be 755 (use "chmod 755 filename"). Make sure
212that the first line of the script contains "#!" starting in column 1
213followed by the pathname of the Python interpreter, for instance:
Guido van Rossum72755611996-03-06 07:20:06 +0000214
215 #!/usr/local/bin/python
216
Guido van Rossum391b4e61996-03-06 19:11:33 +0000217Make sure the Python interpreter exists and is executable by "others".
Guido van Rossum72755611996-03-06 07:20:06 +0000218
Guido van Rossum391b4e61996-03-06 19:11:33 +0000219Make sure that any files your script needs to read or write are
220readable or writable, respectively, by "others" -- their mode should
221be 644 for readable and 666 for writable. This is because, for
222security reasons, the HTTP server executes your script as user
223"nobody", without any special privileges. It can only read (write,
224execute) files that everybody can read (write, execute). The current
225directory at execution time is also different (it is usually the
226server's cgi-bin directory) and the set of environment variables is
227also different from what you get at login. in particular, don't count
228on the shell's search path for executables ($PATH) or the Python
229module search path ($PYTHONPATH) to be set to anything interesting.
Guido van Rossum72755611996-03-06 07:20:06 +0000230
Guido van Rossum391b4e61996-03-06 19:11:33 +0000231If you need to load modules from a directory which is not on Python's
232default module search path, you can change the path in your script,
233before importing other modules, e.g.:
Guido van Rossum72755611996-03-06 07:20:06 +0000234
235 import sys
236 sys.path.insert(0, "/usr/home/joe/lib/python")
237 sys.path.insert(0, "/usr/local/lib/python")
238
239(This way, the directory inserted last will be searched first!)
240
Guido van Rossum391b4e61996-03-06 19:11:33 +0000241Instructions for non-Unix systems will vary; check your HTTP server's
Guido van Rossum72755611996-03-06 07:20:06 +0000242documentation (it will usually have a section on CGI scripts).
243
244
245Testing your CGI script
246-----------------------
247
Guido van Rossum391b4e61996-03-06 19:11:33 +0000248Unfortunately, a CGI script will generally not run when you try it
249from the command line, and a script that works perfectly from the
250command line may fail mysteriously when run from the server. There's
251one reason why you should still test your script from the command
252line: if it contains a syntax error, the python interpreter won't
253execute it at all, and the HTTP server will most likely send a cryptic
254error to the client.
Guido van Rossum72755611996-03-06 07:20:06 +0000255
Guido van Rossum391b4e61996-03-06 19:11:33 +0000256Assuming your script has no syntax errors, yet it does not work, you
257have no choice but to read the next section:
Guido van Rossum72755611996-03-06 07:20:06 +0000258
259
260Debugging CGI scripts
261---------------------
262
Guido van Rossum391b4e61996-03-06 19:11:33 +0000263First of all, check for trivial installation errors -- reading the
264section above on installing your CGI script carefully can save you a
265lot of time. If you wonder whether you have understood the
266installation procedure correctly, try installing a copy of this module
267file (cgi.py) as a CGI script. When invoked as a script, the file
268will dump its environment and the contents of the form in HTML form.
269Give it the right mode etc, and send it a request. If it's installed
270in the standard cgi-bin directory, it should be possible to send it a
271request by entering a URL into your browser of the form:
Guido van Rossum72755611996-03-06 07:20:06 +0000272
273 http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home
274
Guido van Rossum391b4e61996-03-06 19:11:33 +0000275If this gives an error of type 404, the server cannot find the script
276-- perhaps you need to install it in a different directory. If it
277gives another error (e.g. 500), there's an installation problem that
278you should fix before trying to go any further. If you get a nicely
279formatted listing of the environment and form content (in this
280example, the fields should be listed as "addr" with value "At Home"
281and "name" with value "Joe Blow"), the cgi.py script has been
282installed correctly. If you follow the same procedure for your own
283script, you should now be able to debug it.
Guido van Rossum72755611996-03-06 07:20:06 +0000284
Guido van Rossum391b4e61996-03-06 19:11:33 +0000285The next step could be to call the cgi module's test() function from
286your script: replace its main code with the single statement
Guido van Rossum72755611996-03-06 07:20:06 +0000287
288 cgi.test()
289
Guido van Rossum391b4e61996-03-06 19:11:33 +0000290This should produce the same results as those gotten from installing
291the cgi.py file itself.
Guido van Rossum72755611996-03-06 07:20:06 +0000292
Guido van Rossum391b4e61996-03-06 19:11:33 +0000293When an ordinary Python script raises an unhandled exception
294(e.g. because of a typo in a module name, a file that can't be opened,
295etc.), the Python interpreter prints a nice traceback and exits.
296While the Python interpreter will still do this when your CGI script
297raises an exception, most likely the traceback will end up in one of
298the HTTP server's log file, or be discarded altogether.
Guido van Rossum72755611996-03-06 07:20:06 +0000299
Guido van Rossum391b4e61996-03-06 19:11:33 +0000300Fortunately, once you have managed to get your script to execute
301*some* code, it is easy to catch exceptions and cause a traceback to
302be printed. The test() function below in this module is an example.
303Here are the rules:
Guido van Rossum72755611996-03-06 07:20:06 +0000304
Guido van Rossum391b4e61996-03-06 19:11:33 +0000305 1. Import the traceback module (before entering the
306 try-except!)
Guido van Rossum72755611996-03-06 07:20:06 +0000307
Guido van Rossum391b4e61996-03-06 19:11:33 +0000308 2. Make sure you finish printing the headers and the blank
309 line early
Guido van Rossum72755611996-03-06 07:20:06 +0000310
311 3. Assign sys.stderr to sys.stdout
312
313 3. Wrap all remaining code in a try-except statement
314
315 4. In the except clause, call traceback.print_exc()
316
317For example:
318
319 import sys
320 import traceback
321 print "Content-type: text/html"
322 print
323 sys.stderr = sys.stdout
324 try:
325 ...your code here...
326 except:
327 print "\n\n<PRE>"
328 traceback.print_exc()
329
Guido van Rossum391b4e61996-03-06 19:11:33 +0000330Notes: The assignment to sys.stderr is needed because the traceback
331prints to sys.stderr. The print "\n\n<PRE>" statement is necessary to
332disable the word wrapping in HTML.
Guido van Rossum72755611996-03-06 07:20:06 +0000333
Guido van Rossum391b4e61996-03-06 19:11:33 +0000334If you suspect that there may be a problem in importing the traceback
335module, you can use an even more robust approach (which only uses
336built-in modules):
Guido van Rossum72755611996-03-06 07:20:06 +0000337
338 import sys
339 sys.stderr = sys.stdout
340 print "Content-type: text/plain"
341 print
342 ...your code here...
343
Guido van Rossum391b4e61996-03-06 19:11:33 +0000344This relies on the Python interpreter to print the traceback. The
345content type of the output is set to plain text, which disables all
346HTML processing. If your script works, the raw HTML will be displayed
347by your client. If it raises an exception, most likely after the
348first two lines have been printed, a traceback will be displayed.
349Because no HTML interpretation is going on, the traceback will
350readable.
Guido van Rossum72755611996-03-06 07:20:06 +0000351
352Good luck!
353
354
355Common problems and solutions
356-----------------------------
357
Guido van Rossum391b4e61996-03-06 19:11:33 +0000358- Most HTTP servers buffer the output from CGI scripts until the
359script is completed. This means that it is not possible to display a
360progress report on the client's display while the script is running.
Guido van Rossum72755611996-03-06 07:20:06 +0000361
362- Check the installation instructions above.
363
Guido van Rossum391b4e61996-03-06 19:11:33 +0000364- Check the HTTP server's log files. ("tail -f logfile" in a separate
Guido van Rossum72755611996-03-06 07:20:06 +0000365window may be useful!)
366
Guido van Rossum391b4e61996-03-06 19:11:33 +0000367- Always check a script for syntax errors first, by doing something
368like "python script.py".
Guido van Rossum72755611996-03-06 07:20:06 +0000369
370- When using any of the debugging techniques, don't forget to add
371"import sys" to the top of the script.
372
Guido van Rossum391b4e61996-03-06 19:11:33 +0000373- When invoking external programs, make sure they can be found.
374Usually, this means using absolute path names -- $PATH is usually not
375set to a very useful value in a CGI script.
Guido van Rossum72755611996-03-06 07:20:06 +0000376
Guido van Rossum391b4e61996-03-06 19:11:33 +0000377- When reading or writing external files, make sure they can be read
378or written by every user on the system.
Guido van Rossum72755611996-03-06 07:20:06 +0000379
Guido van Rossum391b4e61996-03-06 19:11:33 +0000380- Don't try to give a CGI script a set-uid mode. This doesn't work on
381most systems, and is a security liability as well.
Guido van Rossum72755611996-03-06 07:20:06 +0000382
383
384History
385-------
386
Guido van Rossum391b4e61996-03-06 19:11:33 +0000387Michael McLay started this module. Steve Majewski changed the
388interface to SvFormContentDict and FormContentDict. The multipart
389parsing was inspired by code submitted by Andreas Paepcke. Guido van
390Rossum rewrote, reformatted and documented the module and is currently
391responsible for its maintenance.
Guido van Rossum72755611996-03-06 07:20:06 +0000392
Guido van Rossum0147db01996-03-09 03:16:04 +0000393
394XXX The module is getting pretty heavy with all those docstrings.
395Perhaps there should be a slimmed version that doesn't contain all those
396backwards compatible and debugging classes and functions?
397
Guido van Rossum72755611996-03-06 07:20:06 +0000398"""
399
Guido van Rossum99aa2a41996-07-23 17:27:05 +0000400__version__ = "2.0b2"
Guido van Rossum0147db01996-03-09 03:16:04 +0000401
Guido van Rossum72755611996-03-06 07:20:06 +0000402
403# Imports
404# =======
405
406import string
Guido van Rossum72755611996-03-06 07:20:06 +0000407import sys
408import os
Guido van Rossum72755611996-03-06 07:20:06 +0000409
Guido van Rossum72755611996-03-06 07:20:06 +0000410# Parsing functions
411# =================
412
Guido van Rossum773ab271996-07-23 03:46:24 +0000413def parse(fp=None, environ=os.environ, keep_blank_values=None):
414 """Parse a query in the environment or from a file (default stdin)
415
416 Arguments, all optional:
417
418 fp : file pointer; default: sys.stdin
419
420 environ : environment dictionary; default: os.environ
421
422 keep_blank_values: flag indicating whether blank values in
423 URL encoded forms should be treated as blank strings.
424 A true value inicates that blanks should be retained as
425 blank strings. The default false value indicates that
426 blank values are to be ignored and treated as if they were
427 not included.
428 """
Guido van Rossum7aee3841996-03-07 18:00:44 +0000429 if not fp:
430 fp = sys.stdin
431 if not environ.has_key('REQUEST_METHOD'):
432 environ['REQUEST_METHOD'] = 'GET' # For testing stand-alone
433 if environ['REQUEST_METHOD'] == 'POST':
434 ctype, pdict = parse_header(environ['CONTENT_TYPE'])
435 if ctype == 'multipart/form-data':
Guido van Rossum0147db01996-03-09 03:16:04 +0000436 return parse_multipart(fp, pdict)
Guido van Rossum7aee3841996-03-07 18:00:44 +0000437 elif ctype == 'application/x-www-form-urlencoded':
438 clength = string.atoi(environ['CONTENT_LENGTH'])
439 qs = fp.read(clength)
Guido van Rossum1c9daa81995-09-18 21:52:37 +0000440 else:
Guido van Rossum0147db01996-03-09 03:16:04 +0000441 qs = '' # Unknown content-type
Guido van Rossum7aee3841996-03-07 18:00:44 +0000442 environ['QUERY_STRING'] = qs # XXX Shouldn't, really
443 elif environ.has_key('QUERY_STRING'):
444 qs = environ['QUERY_STRING']
445 else:
446 if sys.argv[1:]:
447 qs = sys.argv[1]
448 else:
449 qs = ""
450 environ['QUERY_STRING'] = qs # XXX Shouldn't, really
Guido van Rossum773ab271996-07-23 03:46:24 +0000451 return parse_qs(qs, keep_blank_values)
Guido van Rossume7808771995-08-07 20:12:09 +0000452
453
Guido van Rossum773ab271996-07-23 03:46:24 +0000454def parse_qs(qs, keep_blank_values=None):
455 """Parse a query given as a string argumen
456
457 Arguments:
458
459 qs : URL-encoded query string to be parsed
460
461 keep_blank_values: flag indicating whether blank values in
462 URL encoded queries should be treated as blank strings.
463 A true value inicates that blanks should be retained as
464 blank strings. The default false value indicates that
465 blank values are to be ignored and treated as if they were
466 not included.
467 """
Guido van Rossum0147db01996-03-09 03:16:04 +0000468 import urllib, regsub
Guido van Rossum7aee3841996-03-07 18:00:44 +0000469 name_value_pairs = string.splitfields(qs, '&')
470 dict = {}
471 for name_value in name_value_pairs:
472 nv = string.splitfields(name_value, '=')
473 if len(nv) != 2:
474 continue
475 name = nv[0]
476 value = urllib.unquote(regsub.gsub('+', ' ', nv[1]))
Guido van Rossum773ab271996-07-23 03:46:24 +0000477 if len(value) or keep_blank_values:
Guido van Rossum7aee3841996-03-07 18:00:44 +0000478 if dict.has_key (name):
479 dict[name].append(value)
480 else:
481 dict[name] = [value]
482 return dict
Guido van Rossum9a22de11995-01-12 12:29:47 +0000483
484
Guido van Rossum0147db01996-03-09 03:16:04 +0000485def parse_multipart(fp, pdict):
Guido van Rossum7aee3841996-03-07 18:00:44 +0000486 """Parse multipart input.
Guido van Rossum9a22de11995-01-12 12:29:47 +0000487
Guido van Rossum7aee3841996-03-07 18:00:44 +0000488 Arguments:
489 fp : input file
Guido van Rossum7aee3841996-03-07 18:00:44 +0000490 pdict: dictionary containing other parameters of conten-type header
Guido van Rossum72755611996-03-06 07:20:06 +0000491
Guido van Rossum0147db01996-03-09 03:16:04 +0000492 Returns a dictionary just like parse_qs(): keys are the field names, each
493 value is a list of values for that field. This is easy to use but not
494 much good if you are expecting megabytes to be uploaded -- in that case,
495 use the FieldStorage class instead which is much more flexible. Note
496 that content-type is the raw, unparsed contents of the content-type
497 header.
498
499 XXX This does not parse nested multipart parts -- use FieldStorage for
500 that.
501
502 XXX This should really be subsumed by FieldStorage altogether -- no
503 point in having two implementations of the same parsing algorithm.
Guido van Rossum72755611996-03-06 07:20:06 +0000504
Guido van Rossum7aee3841996-03-07 18:00:44 +0000505 """
506 import mimetools
507 if pdict.has_key('boundary'):
508 boundary = pdict['boundary']
509 else:
510 boundary = ""
511 nextpart = "--" + boundary
512 lastpart = "--" + boundary + "--"
513 partdict = {}
514 terminator = ""
515
516 while terminator != lastpart:
517 bytes = -1
518 data = None
519 if terminator:
520 # At start of next part. Read headers first.
521 headers = mimetools.Message(fp)
522 clength = headers.getheader('content-length')
523 if clength:
524 try:
525 bytes = string.atoi(clength)
526 except string.atoi_error:
527 pass
528 if bytes > 0:
529 data = fp.read(bytes)
530 else:
531 data = ""
532 # Read lines until end of part.
533 lines = []
534 while 1:
535 line = fp.readline()
536 if not line:
537 terminator = lastpart # End outer loop
538 break
539 if line[:2] == "--":
540 terminator = string.strip(line)
541 if terminator in (nextpart, lastpart):
542 break
Guido van Rossum7aee3841996-03-07 18:00:44 +0000543 lines.append(line)
544 # Done with part.
545 if data is None:
546 continue
547 if bytes < 0:
Guido van Rossum99aa2a41996-07-23 17:27:05 +0000548 if lines:
549 # Strip final line terminator
550 line = lines[-1]
551 if line[-2:] == "\r\n":
552 line = line[:-2]
553 elif line[-1:] == "\n":
554 line = line[:-1]
555 lines[-1] = line
556 data = string.joinfields(lines, "")
Guido van Rossum7aee3841996-03-07 18:00:44 +0000557 line = headers['content-disposition']
558 if not line:
559 continue
560 key, params = parse_header(line)
561 if key != 'form-data':
562 continue
563 if params.has_key('name'):
564 name = params['name']
Guido van Rossum72755611996-03-06 07:20:06 +0000565 else:
Guido van Rossum7aee3841996-03-07 18:00:44 +0000566 continue
Guido van Rossum7aee3841996-03-07 18:00:44 +0000567 if partdict.has_key(name):
568 partdict[name].append(data)
569 else:
570 partdict[name] = [data]
Guido van Rossum72755611996-03-06 07:20:06 +0000571
Guido van Rossum7aee3841996-03-07 18:00:44 +0000572 return partdict
Guido van Rossum9a22de11995-01-12 12:29:47 +0000573
574
Guido van Rossum72755611996-03-06 07:20:06 +0000575def parse_header(line):
Guido van Rossum7aee3841996-03-07 18:00:44 +0000576 """Parse a Content-type like header.
577
578 Return the main content-type and a dictionary of options.
579
580 """
581 plist = map(string.strip, string.splitfields(line, ';'))
582 key = string.lower(plist[0])
583 del plist[0]
584 pdict = {}
585 for p in plist:
586 i = string.find(p, '=')
587 if i >= 0:
588 name = string.lower(string.strip(p[:i]))
589 value = string.strip(p[i+1:])
590 if len(value) >= 2 and value[0] == value[-1] == '"':
591 value = value[1:-1]
592 pdict[name] = value
593 return key, pdict
Guido van Rossum72755611996-03-06 07:20:06 +0000594
595
Guido van Rossum243ddcd1996-03-07 06:33:07 +0000596# Classes for field storage
597# =========================
598
599class MiniFieldStorage:
600
Guido van Rossum0147db01996-03-09 03:16:04 +0000601 """Like FieldStorage, for use when no file uploads are possible."""
Guido van Rossum243ddcd1996-03-07 06:33:07 +0000602
Guido van Rossum7aee3841996-03-07 18:00:44 +0000603 # Dummy attributes
604 filename = None
605 list = None
606 type = None
Guido van Rossum773ab271996-07-23 03:46:24 +0000607 file = None
Guido van Rossum4032c2c1996-03-09 04:04:35 +0000608 type_options = {}
Guido van Rossum7aee3841996-03-07 18:00:44 +0000609 disposition = None
610 disposition_options = {}
611 headers = {}
Guido van Rossum243ddcd1996-03-07 06:33:07 +0000612
Guido van Rossum7aee3841996-03-07 18:00:44 +0000613 def __init__(self, name, value):
614 """Constructor from field name and value."""
615 from StringIO import StringIO
616 self.name = name
617 self.value = value
Guido van Rossum773ab271996-07-23 03:46:24 +0000618 # self.file = StringIO(value)
Guido van Rossum7aee3841996-03-07 18:00:44 +0000619
620 def __repr__(self):
621 """Return printable representation."""
622 return "MiniFieldStorage(%s, %s)" % (`self.name`, `self.value`)
Guido van Rossum243ddcd1996-03-07 06:33:07 +0000623
624
625class FieldStorage:
626
Guido van Rossum7aee3841996-03-07 18:00:44 +0000627 """Store a sequence of fields, reading multipart/form-data.
Guido van Rossum243ddcd1996-03-07 06:33:07 +0000628
Guido van Rossum7aee3841996-03-07 18:00:44 +0000629 This class provides naming, typing, files stored on disk, and
630 more. At the top level, it is accessible like a dictionary, whose
631 keys are the field names. (Note: None can occur as a field name.)
632 The items are either a Python list (if there's multiple values) or
633 another FieldStorage or MiniFieldStorage object. If it's a single
634 object, it has the following attributes:
Guido van Rossum243ddcd1996-03-07 06:33:07 +0000635
Guido van Rossum7aee3841996-03-07 18:00:44 +0000636 name: the field name, if specified; otherwise None
Guido van Rossum243ddcd1996-03-07 06:33:07 +0000637
Guido van Rossum7aee3841996-03-07 18:00:44 +0000638 filename: the filename, if specified; otherwise None; this is the
639 client side filename, *not* the file name on which it is
Guido van Rossum0147db01996-03-09 03:16:04 +0000640 stored (that's a temporary file you don't deal with)
Guido van Rossum243ddcd1996-03-07 06:33:07 +0000641
Guido van Rossum7aee3841996-03-07 18:00:44 +0000642 value: the value as a *string*; for file uploads, this
643 transparently reads the file every time you request the value
644
645 file: the file(-like) object from which you can read the data;
646 None if the data is stored a simple string
647
648 type: the content-type, or None if not specified
649
650 type_options: dictionary of options specified on the content-type
651 line
652
653 disposition: content-disposition, or None if not specified
654
655 disposition_options: dictionary of corresponding options
656
657 headers: a dictionary(-like) object (sometimes rfc822.Message or a
658 subclass thereof) containing *all* headers
659
660 The class is subclassable, mostly for the purpose of overriding
661 the make_file() method, which is called internally to come up with
662 a file open for reading and writing. This makes it possible to
663 override the default choice of storing all files in a temporary
664 directory and unlinking them as soon as they have been opened.
665
666 """
667
Guido van Rossum773ab271996-07-23 03:46:24 +0000668 def __init__(self, fp=None, headers=None, outerboundary="",
669 environ=os.environ, keep_blank_values=None):
Guido van Rossum7aee3841996-03-07 18:00:44 +0000670 """Constructor. Read multipart/* until last part.
671
672 Arguments, all optional:
673
674 fp : file pointer; default: sys.stdin
675
676 headers : header dictionary-like object; default:
677 taken from environ as per CGI spec
678
Guido van Rossum773ab271996-07-23 03:46:24 +0000679 outerboundary : terminating multipart boundary
Guido van Rossum7aee3841996-03-07 18:00:44 +0000680 (for internal use only)
681
Guido van Rossum773ab271996-07-23 03:46:24 +0000682 environ : environment dictionary; default: os.environ
683
684 keep_blank_values: flag indicating whether blank values in
685 URL encoded forms should be treated as blank strings.
686 A true value inicates that blanks should be retained as
687 blank strings. The default false value indicates that
688 blank values are to be ignored and treated as if they were
689 not included.
690
Guido van Rossum7aee3841996-03-07 18:00:44 +0000691 """
692 method = None
Guido van Rossum773ab271996-07-23 03:46:24 +0000693 self.keep_blank_values = keep_blank_values
Guido van Rossum7aee3841996-03-07 18:00:44 +0000694 if environ.has_key('REQUEST_METHOD'):
695 method = string.upper(environ['REQUEST_METHOD'])
696 if not fp and method == 'GET':
697 qs = None
698 if environ.has_key('QUERY_STRING'):
699 qs = environ['QUERY_STRING']
700 from StringIO import StringIO
701 fp = StringIO(qs or "")
702 if headers is None:
703 headers = {'content-type':
704 "application/x-www-form-urlencoded"}
705 if headers is None:
706 headers = {}
707 if environ.has_key('CONTENT_TYPE'):
708 headers['content-type'] = environ['CONTENT_TYPE']
709 if environ.has_key('CONTENT_LENGTH'):
710 headers['content-length'] = environ['CONTENT_LENGTH']
711 self.fp = fp or sys.stdin
712 self.headers = headers
713 self.outerboundary = outerboundary
714
715 # Process content-disposition header
716 cdisp, pdict = "", {}
717 if self.headers.has_key('content-disposition'):
718 cdisp, pdict = parse_header(self.headers['content-disposition'])
719 self.disposition = cdisp
720 self.disposition_options = pdict
721 self.name = None
722 if pdict.has_key('name'):
723 self.name = pdict['name']
724 self.filename = None
725 if pdict.has_key('filename'):
726 self.filename = pdict['filename']
727
728 # Process content-type header
729 ctype, pdict = "text/plain", {}
730 if self.headers.has_key('content-type'):
731 ctype, pdict = parse_header(self.headers['content-type'])
732 self.type = ctype
733 self.type_options = pdict
734 self.innerboundary = ""
735 if pdict.has_key('boundary'):
736 self.innerboundary = pdict['boundary']
737 clen = -1
738 if self.headers.has_key('content-length'):
739 try:
740 clen = string.atoi(self.headers['content-length'])
741 except:
742 pass
743 self.length = clen
744
745 self.list = self.file = None
746 self.done = 0
747 self.lines = []
748 if ctype == 'application/x-www-form-urlencoded':
749 self.read_urlencoded()
750 elif ctype[:10] == 'multipart/':
751 self.read_multi()
752 else:
753 self.read_single()
754
755 def __repr__(self):
756 """Return a printable representation."""
757 return "FieldStorage(%s, %s, %s)" % (
758 `self.name`, `self.filename`, `self.value`)
759
760 def __getattr__(self, name):
761 if name != 'value':
762 raise AttributeError, name
763 if self.file:
764 self.file.seek(0)
765 value = self.file.read()
766 self.file.seek(0)
767 elif self.list is not None:
768 value = self.list
769 else:
770 value = None
771 return value
772
773 def __getitem__(self, key):
774 """Dictionary style indexing."""
775 if self.list is None:
776 raise TypeError, "not indexable"
777 found = []
778 for item in self.list:
779 if item.name == key: found.append(item)
780 if not found:
781 raise KeyError, key
Guido van Rossum0147db01996-03-09 03:16:04 +0000782 if len(found) == 1:
783 return found[0]
784 else:
785 return found
Guido van Rossum7aee3841996-03-07 18:00:44 +0000786
787 def keys(self):
788 """Dictionary style keys() method."""
789 if self.list is None:
790 raise TypeError, "not indexable"
791 keys = []
792 for item in self.list:
793 if item.name not in keys: keys.append(item.name)
794 return keys
795
Guido van Rossum0147db01996-03-09 03:16:04 +0000796 def has_key(self, key):
797 """Dictionary style has_key() method."""
798 if self.list is None:
799 raise TypeError, "not indexable"
800 for item in self.list:
801 if item.name == key: return 1
802 return 0
803
Guido van Rossum7aee3841996-03-07 18:00:44 +0000804 def read_urlencoded(self):
805 """Internal: read data in query string format."""
806 qs = self.fp.read(self.length)
Guido van Rossum773ab271996-07-23 03:46:24 +0000807 dict = parse_qs(qs, self.keep_blank_values)
Guido van Rossum7aee3841996-03-07 18:00:44 +0000808 self.list = []
809 for key, valuelist in dict.items():
810 for value in valuelist:
811 self.list.append(MiniFieldStorage(key, value))
812 self.skip_lines()
813
814 def read_multi(self):
815 """Internal: read a part that is itself multipart."""
816 import rfc822
817 self.list = []
818 part = self.__class__(self.fp, {}, self.innerboundary)
819 # Throw first part away
820 while not part.done:
821 headers = rfc822.Message(self.fp)
822 part = self.__class__(self.fp, headers, self.innerboundary)
823 self.list.append(part)
824 self.skip_lines()
825
826 def read_single(self):
827 """Internal: read an atomic part."""
828 if self.length >= 0:
829 self.read_binary()
830 self.skip_lines()
831 else:
832 self.read_lines()
833 self.file.seek(0)
834
835 bufsize = 8*1024 # I/O buffering size for copy to file
836
837 def read_binary(self):
838 """Internal: read binary data."""
839 self.file = self.make_file('b')
840 todo = self.length
841 if todo >= 0:
842 while todo > 0:
843 data = self.fp.read(min(todo, self.bufsize))
844 if not data:
845 self.done = -1
846 break
847 self.file.write(data)
848 todo = todo - len(data)
849
850 def read_lines(self):
851 """Internal: read lines until EOF or outerboundary."""
852 self.file = self.make_file('')
853 if self.outerboundary:
854 self.read_lines_to_outerboundary()
855 else:
856 self.read_lines_to_eof()
857
858 def read_lines_to_eof(self):
859 """Internal: read lines until EOF."""
860 while 1:
861 line = self.fp.readline()
862 if not line:
863 self.done = -1
864 break
865 self.lines.append(line)
Guido van Rossum7aee3841996-03-07 18:00:44 +0000866 self.file.write(line)
867
868 def read_lines_to_outerboundary(self):
869 """Internal: read lines until outerboundary."""
870 next = "--" + self.outerboundary
871 last = next + "--"
872 delim = ""
873 while 1:
874 line = self.fp.readline()
875 if not line:
876 self.done = -1
877 break
878 self.lines.append(line)
879 if line[:2] == "--":
880 strippedline = string.strip(line)
881 if strippedline == next:
882 break
883 if strippedline == last:
884 self.done = 1
885 break
886 if line[-2:] == "\r\n":
Guido van Rossum99aa2a41996-07-23 17:27:05 +0000887 delim = "\r\n"
Guido van Rossum7aee3841996-03-07 18:00:44 +0000888 line = line[:-2]
889 elif line[-1] == "\n":
Guido van Rossum99aa2a41996-07-23 17:27:05 +0000890 delim = "\n"
Guido van Rossum7aee3841996-03-07 18:00:44 +0000891 line = line[:-1]
Guido van Rossum99aa2a41996-07-23 17:27:05 +0000892 else:
893 delim = ""
Guido van Rossum7aee3841996-03-07 18:00:44 +0000894 self.file.write(delim + line)
Guido van Rossum7aee3841996-03-07 18:00:44 +0000895
896 def skip_lines(self):
897 """Internal: skip lines until outer boundary if defined."""
898 if not self.outerboundary or self.done:
899 return
900 next = "--" + self.outerboundary
901 last = next + "--"
902 while 1:
903 line = self.fp.readline()
904 if not line:
905 self.done = -1
906 break
907 self.lines.append(line)
908 if line[:2] == "--":
909 strippedline = string.strip(line)
910 if strippedline == next:
911 break
912 if strippedline == last:
913 self.done = 1
914 break
915
916 def make_file(self, binary):
917 """Overridable: return a readable & writable file.
918
919 The file will be used as follows:
920 - data is written to it
921 - seek(0)
922 - data is read from it
923
924 The 'binary' argument is 'b' if the file should be created in
925 binary mode (on non-Unix systems), '' otherwise.
926
Guido van Rossum4032c2c1996-03-09 04:04:35 +0000927 This version opens a temporary file for reading and writing,
928 and immediately deletes (unlinks) it. The trick (on Unix!) is
929 that the file can still be used, but it can't be opened by
930 another process, and it will automatically be deleted when it
931 is closed or when the current process terminates.
932
933 If you want a more permanent file, you derive a class which
934 overrides this method. If you want a visible temporary file
935 that is nevertheless automatically deleted when the script
936 terminates, try defining a __del__ method in a derived class
937 which unlinks the temporary files you have created.
Guido van Rossum7aee3841996-03-07 18:00:44 +0000938
939 """
Guido van Rossum4032c2c1996-03-09 04:04:35 +0000940 import tempfile
941 tfn = tempfile.mktemp()
942 f = open(tfn, "w%s+" % binary)
943 os.unlink(tfn)
944 return f
Guido van Rossum243ddcd1996-03-07 06:33:07 +0000945
946
Guido van Rossum4032c2c1996-03-09 04:04:35 +0000947# Backwards Compatibility Classes
948# ===============================
Guido van Rossum9a22de11995-01-12 12:29:47 +0000949
950class FormContentDict:
Guido van Rossum7aee3841996-03-07 18:00:44 +0000951 """Basic (multiple values per field) form content as dictionary.
Guido van Rossum72755611996-03-06 07:20:06 +0000952
Guido van Rossum7aee3841996-03-07 18:00:44 +0000953 form = FormContentDict()
954
955 form[key] -> [value, value, ...]
956 form.has_key(key) -> Boolean
957 form.keys() -> [key, key, ...]
958 form.values() -> [[val, val, ...], [val, val, ...], ...]
959 form.items() -> [(key, [val, val, ...]), (key, [val, val, ...]), ...]
960 form.dict == {key: [val, val, ...], ...}
961
962 """
Guido van Rossum773ab271996-07-23 03:46:24 +0000963 def __init__(self, environ=os.environ):
964 self.dict = parse(environ)
Guido van Rossum7aee3841996-03-07 18:00:44 +0000965 self.query_string = environ['QUERY_STRING']
966 def __getitem__(self,key):
967 return self.dict[key]
968 def keys(self):
969 return self.dict.keys()
970 def has_key(self, key):
971 return self.dict.has_key(key)
972 def values(self):
973 return self.dict.values()
974 def items(self):
975 return self.dict.items()
976 def __len__( self ):
977 return len(self.dict)
Guido van Rossum9a22de11995-01-12 12:29:47 +0000978
979
Guido van Rossum9a22de11995-01-12 12:29:47 +0000980class SvFormContentDict(FormContentDict):
Guido van Rossum7aee3841996-03-07 18:00:44 +0000981 """Strict single-value expecting form content as dictionary.
982
983 IF you only expect a single value for each field, then form[key]
984 will return that single value. It will raise an IndexError if
985 that expectation is not true. IF you expect a field to have
986 possible multiple values, than you can use form.getlist(key) to
987 get all of the values. values() and items() are a compromise:
988 they return single strings where there is a single value, and
989 lists of strings otherwise.
990
991 """
992 def __getitem__(self, key):
993 if len(self.dict[key]) > 1:
994 raise IndexError, 'expecting a single value'
995 return self.dict[key][0]
996 def getlist(self, key):
997 return self.dict[key]
998 def values(self):
999 lis = []
1000 for each in self.dict.values():
1001 if len( each ) == 1 :
1002 lis.append(each[0])
1003 else: lis.append(each)
1004 return lis
1005 def items(self):
1006 lis = []
1007 for key,value in self.dict.items():
1008 if len(value) == 1 :
1009 lis.append((key, value[0]))
1010 else: lis.append((key, value))
1011 return lis
Guido van Rossum9a22de11995-01-12 12:29:47 +00001012
1013
Guido van Rossum9a22de11995-01-12 12:29:47 +00001014class InterpFormContentDict(SvFormContentDict):
Guido van Rossum7aee3841996-03-07 18:00:44 +00001015 """This class is present for backwards compatibility only."""
1016 def __getitem__( self, key ):
1017 v = SvFormContentDict.__getitem__( self, key )
1018 if v[0] in string.digits+'+-.' :
1019 try: return string.atoi( v )
1020 except ValueError:
1021 try: return string.atof( v )
1022 except ValueError: pass
1023 return string.strip(v)
1024 def values( self ):
1025 lis = []
1026 for key in self.keys():
1027 try:
1028 lis.append( self[key] )
1029 except IndexError:
1030 lis.append( self.dict[key] )
1031 return lis
1032 def items( self ):
1033 lis = []
1034 for key in self.keys():
1035 try:
1036 lis.append( (key, self[key]) )
1037 except IndexError:
1038 lis.append( (key, self.dict[key]) )
1039 return lis
Guido van Rossum9a22de11995-01-12 12:29:47 +00001040
1041
Guido van Rossum9a22de11995-01-12 12:29:47 +00001042class FormContent(FormContentDict):
Guido van Rossum7aee3841996-03-07 18:00:44 +00001043 """This class is present for backwards compatibility only."""
Guido van Rossum0147db01996-03-09 03:16:04 +00001044 def values(self, key):
1045 if self.dict.has_key(key) :return self.dict[key]
Guido van Rossum7aee3841996-03-07 18:00:44 +00001046 else: return None
Guido van Rossum0147db01996-03-09 03:16:04 +00001047 def indexed_value(self, key, location):
Guido van Rossum7aee3841996-03-07 18:00:44 +00001048 if self.dict.has_key(key):
1049 if len (self.dict[key]) > location:
1050 return self.dict[key][location]
1051 else: return None
1052 else: return None
Guido van Rossum0147db01996-03-09 03:16:04 +00001053 def value(self, key):
1054 if self.dict.has_key(key): return self.dict[key][0]
Guido van Rossum7aee3841996-03-07 18:00:44 +00001055 else: return None
Guido van Rossum0147db01996-03-09 03:16:04 +00001056 def length(self, key):
1057 return len(self.dict[key])
1058 def stripped(self, key):
1059 if self.dict.has_key(key): return string.strip(self.dict[key][0])
Guido van Rossum7aee3841996-03-07 18:00:44 +00001060 else: return None
1061 def pars(self):
1062 return self.dict
Guido van Rossum9a22de11995-01-12 12:29:47 +00001063
1064
Guido van Rossum72755611996-03-06 07:20:06 +00001065# Test/debug code
1066# ===============
Guido van Rossum9a22de11995-01-12 12:29:47 +00001067
Guido van Rossum773ab271996-07-23 03:46:24 +00001068def test(environ=os.environ):
Guido van Rossum7aee3841996-03-07 18:00:44 +00001069 """Robust test CGI script, usable as main program.
Guido van Rossum9a22de11995-01-12 12:29:47 +00001070
Guido van Rossum7aee3841996-03-07 18:00:44 +00001071 Write minimal HTTP headers and dump all information provided to
1072 the script in HTML form.
1073
1074 """
1075 import traceback
1076 print "Content-type: text/html"
1077 print
1078 sys.stderr = sys.stdout
1079 try:
Guido van Rossum0147db01996-03-09 03:16:04 +00001080 form = FieldStorage() # Replace with other classes to test those
1081 print_form(form)
Guido van Rossum773ab271996-07-23 03:46:24 +00001082 print_environ(environ)
Guido van Rossum7aee3841996-03-07 18:00:44 +00001083 print_directory()
Guido van Rossuma8738a51996-03-14 21:30:28 +00001084 print_arguments()
Guido van Rossum7aee3841996-03-07 18:00:44 +00001085 print_environ_usage()
1086 except:
1087 print "\n\n<PRE>" # Turn off HTML word wrap
1088 traceback.print_exc()
Guido van Rossum9a22de11995-01-12 12:29:47 +00001089
Guido van Rossum773ab271996-07-23 03:46:24 +00001090def print_environ(environ=os.environ):
Guido van Rossum7aee3841996-03-07 18:00:44 +00001091 """Dump the shell environment as HTML."""
1092 keys = environ.keys()
1093 keys.sort()
1094 print
Guido van Rossum503e50b1996-05-28 22:57:20 +00001095 print "<H3>Shell Environment:</H3>"
Guido van Rossum7aee3841996-03-07 18:00:44 +00001096 print "<DL>"
1097 for key in keys:
1098 print "<DT>", escape(key), "<DD>", escape(environ[key])
1099 print "</DL>"
1100 print
Guido van Rossum72755611996-03-06 07:20:06 +00001101
1102def print_form(form):
Guido van Rossum7aee3841996-03-07 18:00:44 +00001103 """Dump the contents of a form as HTML."""
1104 keys = form.keys()
1105 keys.sort()
1106 print
Guido van Rossum503e50b1996-05-28 22:57:20 +00001107 print "<H3>Form Contents:</H3>"
Guido van Rossum7aee3841996-03-07 18:00:44 +00001108 print "<DL>"
1109 for key in keys:
1110 print "<DT>" + escape(key) + ":",
1111 value = form[key]
1112 print "<i>" + escape(`type(value)`) + "</i>"
1113 print "<DD>" + escape(`value`)
1114 print "</DL>"
1115 print
1116
1117def print_directory():
1118 """Dump the current directory as HTML."""
1119 print
1120 print "<H3>Current Working Directory:</H3>"
1121 try:
1122 pwd = os.getcwd()
1123 except os.error, msg:
1124 print "os.error:", escape(str(msg))
1125 else:
1126 print escape(pwd)
1127 print
Guido van Rossum9a22de11995-01-12 12:29:47 +00001128
Guido van Rossuma8738a51996-03-14 21:30:28 +00001129def print_arguments():
1130 print
Guido van Rossum503e50b1996-05-28 22:57:20 +00001131 print "<H3>Command Line Arguments:</H3>"
Guido van Rossuma8738a51996-03-14 21:30:28 +00001132 print
1133 print sys.argv
1134 print
1135
Guido van Rossum9a22de11995-01-12 12:29:47 +00001136def print_environ_usage():
Guido van Rossum7aee3841996-03-07 18:00:44 +00001137 """Dump a list of environment variables used by CGI as HTML."""
1138 print """
Guido van Rossum72755611996-03-06 07:20:06 +00001139<H3>These environment variables could have been set:</H3>
1140<UL>
Guido van Rossum9a22de11995-01-12 12:29:47 +00001141<LI>AUTH_TYPE
1142<LI>CONTENT_LENGTH
1143<LI>CONTENT_TYPE
1144<LI>DATE_GMT
1145<LI>DATE_LOCAL
1146<LI>DOCUMENT_NAME
1147<LI>DOCUMENT_ROOT
1148<LI>DOCUMENT_URI
1149<LI>GATEWAY_INTERFACE
1150<LI>LAST_MODIFIED
1151<LI>PATH
1152<LI>PATH_INFO
1153<LI>PATH_TRANSLATED
1154<LI>QUERY_STRING
1155<LI>REMOTE_ADDR
1156<LI>REMOTE_HOST
1157<LI>REMOTE_IDENT
1158<LI>REMOTE_USER
1159<LI>REQUEST_METHOD
1160<LI>SCRIPT_NAME
1161<LI>SERVER_NAME
1162<LI>SERVER_PORT
1163<LI>SERVER_PROTOCOL
1164<LI>SERVER_ROOT
1165<LI>SERVER_SOFTWARE
1166</UL>
Guido van Rossum7aee3841996-03-07 18:00:44 +00001167In addition, HTTP headers sent by the server may be passed in the
1168environment as well. Here are some common variable names:
1169<UL>
1170<LI>HTTP_ACCEPT
1171<LI>HTTP_CONNECTION
1172<LI>HTTP_HOST
1173<LI>HTTP_PRAGMA
1174<LI>HTTP_REFERER
1175<LI>HTTP_USER_AGENT
1176</UL>
Guido van Rossum9a22de11995-01-12 12:29:47 +00001177"""
1178
Guido van Rossum9a22de11995-01-12 12:29:47 +00001179
Guido van Rossum72755611996-03-06 07:20:06 +00001180# Utilities
1181# =========
Guido van Rossum9a22de11995-01-12 12:29:47 +00001182
Guido van Rossum72755611996-03-06 07:20:06 +00001183def escape(s):
Guido van Rossum7aee3841996-03-07 18:00:44 +00001184 """Replace special characters '&', '<' and '>' by SGML entities."""
Guido van Rossum0147db01996-03-09 03:16:04 +00001185 import regsub
Guido van Rossum7aee3841996-03-07 18:00:44 +00001186 s = regsub.gsub("&", "&amp;", s) # Must be done first!
1187 s = regsub.gsub("<", "&lt;", s)
1188 s = regsub.gsub(">", "&gt;", s)
1189 return s
Guido van Rossum9a22de11995-01-12 12:29:47 +00001190
Guido van Rossum9a22de11995-01-12 12:29:47 +00001191
Guido van Rossum72755611996-03-06 07:20:06 +00001192# Invoke mainline
1193# ===============
1194
1195# Call test() when this file is run as a script (not imported as a module)
1196if __name__ == '__main__':
Guido van Rossum7aee3841996-03-07 18:00:44 +00001197 test()