rest25/library/cgi.rst => rest262/library/cgi.rst
f1
2:mod:`cgi` --- Common Gateway Interface support.
3================================================
4
5.. module:: cgi
n6- 
n6+   :synopsis: Helpers for running Python scripts via the Common Gateway Interface.
7- 
8
9
10.. index::
11   pair: WWW; server
12   pair: CGI; protocol
13   pair: HTTP; protocol
14   pair: MIME; headers
15   single: URL
n16- 
17-.. index:: single: Common Gateway Interface
15+   single: Common Gateway Interface
18
19Support module for Common Gateway Interface (CGI) scripts.
n20- 
21-.. % 
22
23This module defines a number of utilities for use by CGI scripts written in
24Python.
25
26
27Introduction
28------------
29
57nicely formatted text with header, in-line images, etc. Here's Python code that
58prints a simple piece of HTML::
59
60   print "<TITLE>CGI script output</TITLE>"
61   print "<H1>This is my first CGI script</H1>"
62   print "Hello, world!"
63
64
n61+.. _using-the-cgi-module:
62+ 
65Using the cgi module
66--------------------
n67- 
68-.. _using the cgi module:
69
70Begin by writing ``import cgi``.  Do not use ``from cgi import *`` --- the
71module defines all sorts of names for its own use or for backward compatibility
72that you don't want in your namespace.
73
n74-When you write a new script, consider adding the line::
n70+When you write a new script, consider adding these lines::
75
n76-   import cgitb; cgitb.enable()
n72+   import cgitb
73+   cgitb.enable()
77
78This activates a special exception handler that will display detailed reports in
79the Web browser if any errors occur.  If you'd rather not show the guts of your
80program to users of your script, you can have the reports saved to files
n81-instead, with a line like this::
n78+instead, with code like this::
82
n80+   import cgitb
83-   import cgitb; cgitb.enable(display=0, logdir="/tmp")
81+   cgitb.enable(display=0, logdir="/tmp")
84
85It's very helpful to use this feature during script development. The reports
86produced by :mod:`cgitb` provide information that can save you a lot of time in
87tracking down bugs.  You can always remove the ``cgitb`` line later when you
88have tested your script and are confident that it works correctly.
89
90To get at submitted form data, it's best to use the :class:`FieldStorage` class.
91The other classes defined in this module are provided mostly for backward
146   if fileitem.file:
147       # It's an uploaded file; count lines
148       linecount = 0
149       while 1:
150           line = fileitem.file.readline()
151           if not line: break
152           linecount = linecount + 1
153
n152+If an error is encountered when obtaining the contents of an uploaded file
153+(for example, when the user interrupts the form submission by clicking on
154+a Back or Cancel button) the :attr:`done` attribute of the object for the
155+field will be set to the value -1.
156+ 
154The file upload draft standard entertains the possibility of uploading multiple
155files from one field (using a recursive :mimetype:`multipart/\*` encoding).
156When this occurs, the item will be a dictionary-like :class:`FieldStorage` item.
157This can be determined by testing its :attr:`type` attribute, which should be
158:mimetype:`multipart/form-data` (or perhaps another MIME type matching
159:mimetype:`multipart/\*`).  In this case, it can be iterated over recursively
160just like the top-level form object.
161
162When a form is submitted in the "old" format (as the query string or as a single
163data part of type :mimetype:`application/x-www-form-urlencoded`), the items will
164actually be instances of the class :class:`MiniFieldStorage`.  In this case, the
165:attr:`list`, :attr:`file`, and :attr:`filename` attributes are always ``None``.
166
n170+A form submitted via POST that also has a query string will contain both
171+:class:`FieldStorage` and :class:`MiniFieldStorage` items.
167
168Higher Level Interface
169----------------------
170
171.. versionadded:: 2.2
172
173The previous section explains how to read CGI form data using the
174:class:`FieldStorage` class.  This section describes a higher level interface
175which was added to this class to allow one to do it in a more readable and
176intuitive way.  The interface doesn't make the techniques described in previous
177sections obsolete --- they are still useful to process file uploads efficiently,
178for example.
179
n180-.. % XXX: Is this true ?
n185+.. XXX: Is this true ?
181
182The interface consists of two simple methods. Using the methods you can process
183form data in a generic way, without the need to worry whether only one or more
184values were posted under one name.
185
186In the previous section, you learned to write following code anytime you
187expected a user to post more than one value under one name::
188
244   user = form.getfirst("user", "").upper()    # This way it's safe.
245   for item in form.getlist("item"):
246       do_something(item)
247
248
249Old classes
250-----------
251
n257+.. deprecated:: 2.6
258+ 
252-These classes, present in earlier versions of the :mod:`cgi` module, are still
259+   These classes, present in earlier versions of the :mod:`cgi` module, are
253-supported for backward compatibility.  New applications should use the
260+   still supported for backward compatibility.  New applications should use the
254-:class:`FieldStorage` class.
261+   :class:`FieldStorage` class.
255
256:class:`SvFormContentDict` stores single value form content as dictionary; it
257assumes each field name occurs in the form only once.
258
259:class:`FormContentDict` stores multiple value form content as a dictionary (the
260form items are lists of values).  Useful if your form contains multiple fields
261with the same name.
262
263Other classes (:class:`FormContent`, :class:`InterpFormContentDict`) are present
n264-for backwards compatibility with really old applications only. If you still use
n271+for backwards compatibility with really old applications only.
265-these and would be inconvenienced when they disappeared from a next version of
266-this module, drop me a note.
267
n273+ 
274+.. _functions-in-cgi-module:
268
269Functions
270---------
271
n272-.. _functions in cgi module:
273- 
274These are useful if you want more control, or if you want to employ some of the
275algorithms implemented in this module in other circumstances.
276
277
278.. function:: parse(fp[, keep_blank_values[, strict_parsing]])
279
280   Parse a query in the environment or from a file (the file defaults to
281   ``sys.stdin``).  The *keep_blank_values* and *strict_parsing* parameters are
n282-   passed to :func:`parse_qs` unchanged.
n287+   passed to :func:`urlparse.parse_qs` unchanged.
283
284
285.. function:: parse_qs(qs[, keep_blank_values[, strict_parsing]])
286
n287-   Parse a query string given as a string argument (data of type
n292+   This function is deprecated in this module. Use :func:`urlparse.parse_qs`
288-   :mimetype:`application/x-www-form-urlencoded`).  Data are returned as a
293+   instead. It is maintained here only for backward compatiblity.
289-   dictionary.  The dictionary keys are the unique query variable names and the
290-   values are lists of values for each name.
291- 
292-   The optional argument *keep_blank_values* is a flag indicating whether blank
293-   values in URL encoded queries should be treated as blank strings.   A true value
294-   indicates that blanks should be retained as  blank strings.  The default false
295-   value indicates that blank values are to be ignored and treated as if they were
296-   not included.
297- 
298-   The optional argument *strict_parsing* is a flag indicating what to do with
299-   parsing errors.  If false (the default), errors are silently ignored.  If true,
300-   errors raise a :exc:`ValueError` exception.
301- 
302-   Use the :func:`urllib.urlencode` function to convert such dictionaries into
303-   query strings.
304- 
305
306.. function:: parse_qsl(qs[, keep_blank_values[, strict_parsing]])
307
n308-   Parse a query string given as a string argument (data of type
n297+   This function is deprecated in this module. Use :func:`urlparse.parse_qsl`
309-   :mimetype:`application/x-www-form-urlencoded`).  Data are returned as a list of
298+   instead. It is maintained here only for backward compatiblity.
310-   name, value pairs.
311- 
312-   The optional argument *keep_blank_values* is a flag indicating whether blank
313-   values in URL encoded queries should be treated as blank strings.   A true value
314-   indicates that blanks should be retained as  blank strings.  The default false
315-   value indicates that blank values are to be ignored and treated as if they were
316-   not included.
317- 
318-   The optional argument *strict_parsing* is a flag indicating what to do with
319-   parsing errors.  If false (the default), errors are silently ignored.  If true,
320-   errors raise a :exc:`ValueError` exception.
321- 
322-   Use the :func:`urllib.urlencode` function to convert such lists of pairs into
323-   query strings.
324- 
325
326.. function:: parse_multipart(fp, pdict)
327
328   Parse input of type :mimetype:`multipart/form-data` (for  file uploads).
329   Arguments are *fp* for the input file and *pdict* for a dictionary containing
330   other parameters in the :mailheader:`Content-Type` header.
331
n332-   Returns a dictionary just like :func:`parse_qs` keys are the field names, each
n306+   Returns a dictionary just like :func:`urlparse.parse_qs` keys are the field names, each
333   value is a list of values for that field.  This is easy to use but not much good
334   if you are expecting megabytes to be uploaded --- in that case, use the
335   :class:`FieldStorage` class instead which is much more flexible.
336
337   Note that this does not parse nested multipart parts --- use
338   :class:`FieldStorage` for that.
339
340
493reason: of a typo in a module name, a file that can't be opened, etc.), the
494Python interpreter prints a nice traceback and exits.  While the Python
495interpreter will still do this when your CGI script raises an exception, most
496likely the traceback will end up in one of the HTTP server's log files, or be
497discarded altogether.
498
499Fortunately, once you have managed to get your script to execute *some* code,
500you can easily send tracebacks to the Web browser using the :mod:`cgitb` module.
n501-If you haven't done so already, just add the line::
n475+If you haven't done so already, just add the lines::
502
n503-   import cgitb; cgitb.enable()
n477+   import cgitb
478+   cgitb.enable()
504
505to the top of your script.  Then try running it again; when a problem occurs,
506you should see a detailed report that will likely make apparent the cause of the
507crash.
508
509If you suspect that there may be a problem in importing the :mod:`cgitb` module,
510you can use an even more robust approach (which only uses built-in modules)::
511
551  userid for a web server's ``suexec`` feature.
552
553* Don't try to give a CGI script a set-uid mode.  This doesn't work on most
554  systems, and is a security liability as well.
555
556.. rubric:: Footnotes
557
558.. [#] Note that some recent versions of the HTML specification do state what order the
t559-   field values should be supplied in, but knowing whether a request was received
t534+   field values should be supplied in, but knowing whether a request was
560-   from a conforming browser, or even from a browser at all, is tedious and error-
535+   received from a conforming browser, or even from a browser at all, is tedious
561-   prone.
536+   and error-prone.
562
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op