home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 5 / DATAFILE_PDCD5.iso / utilities / p / python / !Python / Lib / NetLib / py / cgi < prev    next >
Text File  |  1996-10-24  |  40KB  |  1,286 lines

  1. #!/usr/local/bin/python
  2.  
  3. """Support module for CGI (Common Gateway Interface) scripts.
  4.  
  5. This module defines a number of utilities for use by CGI scripts
  6. written in Python.
  7.  
  8.  
  9. Introduction
  10. ------------
  11.  
  12. A CGI script is invoked by an HTTP server, usually to process user
  13. input submitted through an HTML <FORM> or <ISINPUT> element.
  14.  
  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.
  20.  
  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).
  29.  
  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:
  34.  
  35.     print "Content-type: text/html"    # HTML is following
  36.     print                # blank line, end of headers
  37.  
  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:
  41.  
  42.     print "<TITLE>CGI script output</TITLE>"
  43.     print "<H1>This is my first CGI script</H1>"
  44.     print "Hello, world!"
  45.  
  46. (It may not be fully legal HTML according to the letter of the
  47. standard, but any browser will understand it.)
  48.  
  49.  
  50. Using the cgi module
  51. --------------------
  52.  
  53. Begin by writing "import cgi".  Don't use "from cgi import *" -- the
  54. module defines all sorts of names for its own use or for backward 
  55. compatibility that you don't want in your namespace.
  56.  
  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.
  63.  
  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:
  68.  
  69.     form = cgi.FieldStorage()
  70.     form_ok = 0
  71.     if form.has_key("name") and form.has_key("addr"):
  72.         if form["name"].value != "" and form["addr"].value != "":
  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
  78.     ...further form processing here...
  79.  
  80. Here the fields, accessed through form[key], are themselves instances
  81. of FieldStorage (or MiniFieldStorage, depending on the form encoding).
  82.  
  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"]
  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
  104.         usernames = username.value
  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.  
  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.  
  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.
  133.  
  134.  
  135. Old classes
  136. -----------
  137.  
  138. These classes, present in earlier versions of the cgi module, are still 
  139. supported for backward compatibility.  New applications should use the
  140. FieldStorage class.
  141.  
  142. SvFormContentDict: single value form content as dictionary; assumes each 
  143. field name occurs in the form only once.
  144.  
  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.
  148.  
  149. Other classes (FormContent, InterpFormContentDict) are present for
  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.
  153.  
  154.  
  155. Functions
  156. ---------
  157.  
  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.
  161.  
  162. parse(fp): parse a form into a Python dictionary.
  163.  
  164. parse_qs(qs): parse a query string (data of type 
  165. application/x-www-form-urlencoded).
  166.  
  167. parse_multipart(fp, pdict): parse input of type multipart/form-data (for 
  168. file uploads).
  169.  
  170. parse_header(string): parse a header like Content-type into a main
  171. value and a dictionary of parameters.
  172.  
  173. test(): complete test program.
  174.  
  175. print_environ(): format the shell environment in HTML.
  176.  
  177. print_form(form): format a form in HTML.
  178.  
  179. print_environ_usage(): print a list of useful environment variables in
  180. HTML.
  181.  
  182. escape(): convert the characters "&", "<" and ">" to HTML-safe
  183. sequences.  Use this if you need to display text that might contain
  184. such characters in HTML.  To translate URLs for inclusion in the HREF
  185. attribute of an <A> tag, use urllib.quote().
  186.  
  187. log(fmt, ...): write a line to a log file; see docs for initlog().
  188.  
  189.  
  190. Caring about security
  191. ---------------------
  192.  
  193. There's one important rule: if you invoke an external program (e.g.
  194. via the os.system() or os.popen() functions), make very sure you don't
  195. pass arbitrary strings received from the client to the shell.  This is
  196. a well-known security hole whereby clever hackers anywhere on the web
  197. can exploit a gullible CGI script to invoke arbitrary shell commands.
  198. Even parts of the URL or field names cannot be trusted, since the
  199. request doesn't have to come from your form!
  200.  
  201. To be on the safe side, if you must pass a string gotten from a form
  202. to a shell command, you should make sure the string contains only
  203. alphanumeric characters, dashes, underscores, and periods.
  204.  
  205.  
  206. Installing your CGI script on a Unix system
  207. -------------------------------------------
  208.  
  209. Read the documentation for your HTTP server and check with your local
  210. system administrator to find the directory where CGI scripts should be
  211. installed; usually this is in a directory cgi-bin in the server tree.
  212.  
  213. Make sure that