Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(169253)

Side by Side Diff: Doc/library/cgi.rst

Issue 11352: Update cgi module doc
Patch Set: Created 7 years, 7 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
View unified diff | Download patch
« no previous file with comments | « no previous file | Doc/make.bat » ('j') | Doc/make.bat » ('J')
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 :mod:`cgi` --- Common Gateway Interface support 1 :mod:`cgi` --- Common Gateway Interface support
2 =============================================== 2 ===============================================
3 3
4 .. module:: cgi 4 .. module:: cgi
5 :synopsis: Helpers for running Python scripts via the Common Gateway Interfac e. 5 :synopsis: Helpers for running Python scripts via the Common Gateway Interfac e.
6 6
7 7
8 .. index:: 8 .. index::
9 pair: WWW; server 9 pair: WWW; server
10 pair: CGI; protocol 10 pair: CGI; protocol
11 pair: HTTP; protocol 11 pair: HTTP; protocol
12 pair: MIME; headers 12 pair: MIME; headers
13 single: URL 13 single: URL
14 single: Common Gateway Interface 14 single: Common Gateway Interface
15 15
16 **Source code:** :source:`Lib/cgi.py` 16 **Source code:** :source:`Lib/cgi.py`
17 17
18 -------------- 18 --------------
19 19
20 Support module for Common Gateway Interface (CGI) scripts. 20 Support module for Common Gateway Interface (CGI) scripts.
21 21
22 This module defines a number of utilities for use by CGI scripts written in 22 This module defines a number of utilities for use by CGI scripts written in
23 Python. 23 Python.
24 24
25 25
26 Introduction 26 Introduction
27 ------------ 27 ------------
28 28
29 .. _cgi-intro: 29 .. _cgi-intro:
30 30
31 A CGI script is invoked by an HTTP server, usually to process user input 31 A CGI script is invoked by an HTTP server, usually to process user input
32 submitted through an HTML ``<FORM>`` or ``<ISINDEX>`` element. 32 submitted through an HTML ``<FORM>`` element.
Jim.J.Jewett 2014/03/20 20:37:33 Marking for posterity: ISINDEX is obsolete, but s
33 33
34 Most often, CGI scripts live in the server's special :file:`cgi-bin` directory. 34 Most often, CGI scripts live in the server's special :file:`cgi-bin` directory.
35 The HTTP server places all sorts of information about the request (such as the 35 The HTTP server places all sorts of information about the request (such as the
36 client's hostname, the requested URL, the query string, and lots of other 36 client's hostname, the requested URL, the query string, and lots of other
37 goodies) in the script's shell environment, executes the script, and sends the 37 goodies) in the script's shell environment, executes the script, and sends the
38 script's output back to the client. 38 script's output back to the client.
39 39
40 The script's input is connected to the client too, and sometimes the form data 40 The script's input is connected to the client too, and sometimes the form data
41 is read this way; at other times the form data is passed via the "query string" 41 is read this way; at other times the form data is passed via the "query string"
42 part of the URL. This module is intended to take care of the different cases 42 part of the URL. This module is intended to take care of the different cases
43 and provide a simpler interface to the Python script. It also provides a number 43 and provide a simpler interface to the Python script. It also provides a number
44 of utilities that help in debugging scripts, and the latest addition is support 44 of utilities that help in debugging scripts.
45 for file uploads from a form (if your browser supports it).
46 45
47 The output of a CGI script should consist of two sections, separated by a blank 46 The output of a CGI script should consist of two sections, separated by a blank
48 line. The first section contains a number of headers, telling the client what 47 line. The first section contains a number of headers, telling the client what
49 kind of data is following. Python code to generate a minimal header section 48 kind of data is following. Python code to generate a minimal header section
50 looks like this:: 49 looks like this::
51 50
52 print("Content-Type: text/html") # HTML is following 51 print("Content-Type: text/html") # HTML is following
53 print() # blank line, end of headers 52 print() # blank line, end of headers
54 53
55 The second section is usually HTML, which allows the client software to display 54 The second section is usually HTML, which allows the client software to display
(...skipping 23 matching lines...) Expand all
79 instead, with code like this:: 78 instead, with code like this::
80 79
81 import cgitb 80 import cgitb
82 cgitb.enable(display=0, logdir="/tmp") 81 cgitb.enable(display=0, logdir="/tmp")
83 82
84 It's very helpful to use this feature during script development. The reports 83 It's very helpful to use this feature during script development. The reports
85 produced by :mod:`cgitb` provide information that can save you a lot of time in 84 produced by :mod:`cgitb` provide information that can save you a lot of time in
86 tracking down bugs. You can always remove the ``cgitb`` line later when you 85 tracking down bugs. You can always remove the ``cgitb`` line later when you
87 have tested your script and are confident that it works correctly. 86 have tested your script and are confident that it works correctly.
88 87
89 To get at submitted form data, use the :class:`FieldStorage` class. If the form 88 To get at submitted form data, use the :class:`FieldStorage` class.
90 contains non-ASCII characters, use the *encoding* keyword parameter set to the
91 value of the encoding defined for the document. It is usually contained in the
92 META tag in the HEAD section of the HTML document or by the
93 :mailheader:`Content-Type` header). This reads the form contents from the
94 standard input or the environment (depending on the value of various
95 environment variables set according to the CGI standard). Since it may consume
96 standard input, it should be instantiated only once.
97 89
98 The :class:`FieldStorage` instance can be indexed like a Python dictionary. 90 .. class:: FieldStorage([encoding[,errors[,keep_blank_values]]])
berkerpeksag 2014/03/19 07:45:59 Nit: Please add a space after commas.
99 It allows membership testing with the :keyword:`in` operator, and also supports 91
100 the standard dictionary method :meth:`keys` and the built-in function 92 Creating an instance of this class reads the form contents from the
101 :func:`len`. Form fields containing empty strings are ignored and do not appear 93 standard input or the environment (depending on the value of various
102 in the dictionary; to keep such values, provide a true value for the optional 94 environment variables set according to the CGI standard). Since it may
103 *keep_blank_values* keyword parameter when creating the :class:`FieldStorage` 95 consume standard input, it should be instantiated only once.
Jim.J.Jewett 2014/03/20 20:37:33 Once once per what? Per Request? Per process? P
104 instance. 96
97 If the form contains non-ASCII characters, use the *encoding* keyword
98 parameter set to the value of the encoding defined for the document. It
99 is usually contained in the META tag in the HEAD section of the HTML
berkerpeksag 2014/03/19 07:45:59 META tag -> ``<meta>`` element
berkerpeksag 2014/03/19 07:45:59 I would drop the "in the HEAD section" part.
Jim.J.Jewett 2014/03/20 20:37:33 Also, "in a META element", rather than *the* eleme
100 document or in the :mailheader:`Content-Type` header. The *errors*
101 argument indicates how to manage encoding errors (see the :mod:`str`
berkerpeksag 2014/03/19 07:45:59 You could add a link to http://docs.python.org/3.4
102 documentation)
103
104 Form fields containing empty strings are ignored and do not appear
105 in the dictionary; to keep such values, provide a true value for the
berkerpeksag 2014/03/19 07:45:59 true -> ``True``
106 optional *keep_blank_values* keyword parameter when creating the
107 :class:`FieldStorage` instance.
108
109 The :class:`FieldStorage` instance is a dictionary-like object, mapping each
110 form field name to an object that can be :
berkerpeksag 2014/03/19 07:45:59 Remove the space before the colon.
111
112 * another instance of :class:`FieldStorage` for data sent in the body of a
berkerpeksag 2014/03/19 07:45:59 I would remove the indentation here. It's looks a
113 POST request with a :mimetype:`multipart` encoding type
114
115 * an instance of the :class:`MiniFieldStorage` class for data sent as the
116 URL query string or as a single data part of type
117 :mimetype:`application/x-www-form-urlencoded`
118
119 * a list of :class:`FieldStorage` or :class:`MiniFieldStorage` in the case
120 of multiple fields with the same name (see next section)
121
122 A form submitted via POST that also has a query string will contain both
berkerpeksag 2014/03/19 07:45:59 "via POST request"?
123 :class:`FieldStorage` and :class:`MiniFieldStorage` items.
124
125 In all cases, the object associated to a field name has an attribute
126 :attr:`value`. It is set to
127
128 * the field value as a string, or as bytes for file uploads, if there is a
129 single value for this field name
130
131 * the list of values if there are several values for this field name
132
133 For instances of :class:`FieldStorage` the value can be obtained by the method
134
135 .. method:: FieldStorage.getvalue(name[,default])
136
137 Returns the value for the specified field name ; the optional argument
berkerpeksag 2014/03/19 07:45:59 Returns -> Return
berkerpeksag 2014/03/19 07:45:59 "field name ;" -> field *name*;
138 *default* is returned if the requested name is not present.
berkerpeksag 2014/03/19 07:45:59 *name*
105 139
106 For instance, the following code (which assumes that the 140 For instance, the following code (which assumes that the
107 :mailheader:`Content-Type` header and blank line have already been printed) 141 :mailheader:`Content-Type` header and blank line have already been printed)
108 checks that the fields ``name`` and ``addr`` are both set to a non-empty 142 checks that the fields ``name`` and ``addr`` are both set to a non-empty
109 string:: 143 string::
110 144
111 form = cgi.FieldStorage() 145 form = cgi.FieldStorage()
112 if "name" not in form or "addr" not in form: 146 if "name" not in form or "addr" not in form:
113 print("<H1>Error</H1>") 147 print("<H1>Error</H1>")
114 print("Please fill in the name and addr fields.") 148 print("Please fill in the name and addr fields.")
115 return 149 return
116 print("<p>name:", form["name"].value) 150 print("<p>name:", form["name"].value)
117 print("<p>addr:", form["addr"].value) 151 print("<p>addr:", form["addr"].value)
118 ...further form processing here... 152 ...further form processing here...
119 153
120 Here the fields, accessed through ``form[key]``, are themselves instances of 154 Here the fields, accessed through ``form[key]``, are themselves instances of
121 :class:`FieldStorage` (or :class:`MiniFieldStorage`, depending on the form 155 :class:`FieldStorage` (or :class:`MiniFieldStorage`, depending on the form
122 encoding). The :attr:`value` attribute of the instance yields the string value 156 encoding). The :attr:`value` attribute of the instance yields the string value
123 of the field. The :meth:`getvalue` method returns this string value directly; 157 of the field
berkerpeksag 2014/03/19 07:45:59 Needs a dot.
124 it also accepts an optional second argument as a default to return if the
125 requested key is not present.
126 158
127 If the submitted form data contains more than one field with the same name, the 159 Multiple fields with the same name
128 object retrieved by ``form[key]`` is not a :class:`FieldStorage` or 160 ----------------------------------
129 :class:`MiniFieldStorage` instance but a list of such instances. Similarly, in 161
130 this situation, ``form.getvalue(key)`` would return a list of strings. If you 162 The submitted form data may contain more than one field with the same name.
131 expect this possibility (when your HTML form contains multiple fields with the 163 This situation is common for example when a form contains a group of multiple
132 same name), use the :func:`getlist` function, which always returns a list of 164 checkboxes with the same name::
berkerpeksag 2014/03/19 07:45:59 I would use ``.. code-block:: html`` here.
133 values (so that you do not need to special-case the single item case). For 165
134 example, this code concatenates any number of username fields, separated by 166 <input type="checkbox" name="item" value="1" />
berkerpeksag 2014/03/19 07:46:00 "/>" is not the best practice in HTML 5 these days
135 commas:: 167 <input type="checkbox" name="item" value="2" />
168
169 In this case, the object retrieved by ``form["item"]`` is not a
170 :class:`FieldStorage` or :class:`MiniFieldStorage` instance but a list of such
171 instances. Similarly, in this situation, ``form.getvalue(key)`` would return
172 a list of strings. If you expect this possibility (when your HTML form
173 contains multiple fields with the same name), use the following methods:
174
175 .. method:: FieldStorage.getlist(name)
176
177 This method always returns a list of values associated with form field *name* .
178 The method returns an empty list if no such form field or value exists for
179 *name*. It returns a list consisting of one item if only one such value exis ts.
180
181
182 .. method:: FieldStorage.getfirst(name, default=None)
berkerpeksag 2014/03/19 07:46:00 [, default]
183
184 This method always returns only one value associated with form field *name*.
185 The method returns only the first value in case that more values were posted
186 under such name. Please note that the order in which the values are received
187 may vary from browser to browser and should not be counted on. [#]_ If no su ch
188 form field or value exists then the method returns the value specified by the
189 optional parameter *default*. This parameter defaults to ``None`` if not
190 specified.
191
192
193 For example, this code concatenates any number of fields called ``username``,
194 separated by commas::
136 195
137 value = form.getlist("username") 196 value = form.getlist("username")
138 usernames = ",".join(value) 197 usernames = ",".join(value)
139 198
199 Using these methods you can write code that handles all cases without having to
200 test if the value is a single instance or a list of instances::
201
202 import cgi
203 form = cgi.FieldStorage()
204 user = form.getfirst("user", "").upper() # This way it's safe.
205 for item in form.getlist("item"):
206 do_something(item)
207
208
209 File uploads
210 ------------
211
140 If a field represents an uploaded file, accessing the value via the 212 If a field represents an uploaded file, accessing the value via the
141 :attr:`value` attribute or the :func:`getvalue` method reads the entire file in 213 :attr:`value` attribute or the :func:`getvalue` method reads the entire file in
142 memory as bytes. This may not be what you want. You can test for an uploaded 214 memory as bytes. This may not be what you want. You can test for an uploaded
143 file by testing either the :attr:`filename` attribute or the :attr:`!file` 215 file by testing either the :attr:`filename` attribute or the :attr:`!file`
144 attribute. You can then read the data at leisure from the :attr:`!file` 216 attribute. You can then read the data at leisure from the :attr:`!file`
145 attribute (the :func:`read` and :func:`readline` methods will return bytes):: 217 attribute (the :func:`read` and :func:`readline` methods will return bytes)::
146 218
147 fileitem = form["userfile"] 219 fileitem = form["userfile"]
148 if fileitem.file: 220 if fileitem.file:
149 # It's an uploaded file; count lines 221 # It's an uploaded file; count lines
150 linecount = 0 222 linecount = 0
151 while True: 223 while True:
152 line = fileitem.file.readline() 224 line = fileitem.file.readline()
153 if not line: break 225 if not line: break
154 linecount = linecount + 1 226 linecount = linecount + 1
155 227
156 If an error is encountered when obtaining the contents of an uploaded file 228 If an error is encountered when obtaining the contents of an uploaded file
157 (for example, when the user interrupts the form submission by clicking on 229 (for example, when the user interrupts the form submission by clicking on
158 a Back or Cancel button) the :attr:`done` attribute of the object for the 230 a Back or Cancel button) the :attr:`done` attribute of the object for the
159 field will be set to the value -1. 231 field will be set to the value -1.
160 232
161 The file upload draft standard entertains the possibility of uploading multiple 233 The file upload draft standard entertains the possibility of uploading multiple
162 files from one field (using a recursive :mimetype:`multipart/\*` encoding). 234 files from one field (using a recursive :mimetype:`multipart/\*` encoding).
163 When this occurs, the item will be a dictionary-like :class:`FieldStorage` item. 235 When this occurs, the item will be a dictionary-like :class:`FieldStorage` item.
164 This can be determined by testing its :attr:`!type` attribute, which should be 236 This can be determined by testing its :attr:`!type` attribute, which should be
165 :mimetype:`multipart/form-data` (or perhaps another MIME type matching 237 :mimetype:`multipart/form-data` (or perhaps another MIME type matching
166 :mimetype:`multipart/\*`). In this case, it can be iterated over recursively 238 :mimetype:`multipart/\*`). In this case, it can be iterated over recursively
167 just like the top-level form object. 239 just like the top-level form object.
168
169 When a form is submitted in the "old" format (as the query string or as a single
170 data part of type :mimetype:`application/x-www-form-urlencoded`), the items will
171 actually be instances of the class :class:`MiniFieldStorage`. In this case, the
172 :attr:`!list`, :attr:`!file`, and :attr:`filename` attributes are always ``None` `.
173
174 A form submitted via POST that also has a query string will contain both
175 :class:`FieldStorage` and :class:`MiniFieldStorage` items.
176
177 Higher Level Interface
178 ----------------------
179
180 The previous section explains how to read CGI form data using the
181 :class:`FieldStorage` class. This section describes a higher level interface
182 which was added to this class to allow one to do it in a more readable and
183 intuitive way. The interface doesn't make the techniques described in previous
184 sections obsolete --- they are still useful to process file uploads efficiently,
185 for example.
186
187 .. XXX: Is this true ?
188
189 The interface consists of two simple methods. Using the methods you can process
190 form data in a generic way, without the need to worry whether only one or more
191 values were posted under one name.
192
193 In the previous section, you learned to write following code anytime you
194 expected a user to post more than one value under one name::
195
196 item = form.getvalue("item")
197 if isinstance(item, list):
198 # The user is requesting more than one item.
199 else:
200 # The user is requesting only one item.
201
202 This situation is common for example when a form contains a group of multiple
203 checkboxes with the same name::
204
205 <input type="checkbox" name="item" value="1" />
206 <input type="checkbox" name="item" value="2" />
207
208 In most situations, however, there's only one form control with a particular
209 name in a form and then you expect and need only one value associated with this
210 name. So you write a script containing for example this code::
211
212 user = form.getvalue("user").upper()
213
214 The problem with the code is that you should never expect that a client will
215 provide valid input to your scripts. For example, if a curious user appends
216 another ``user=foo`` pair to the query string, then the script would crash,
217 because in this situation the ``getvalue("user")`` method call returns a list
218 instead of a string. Calling the :meth:`~str.upper` method on a list is not val id
219 (since lists do not have a method of this name) and results in an
220 :exc:`AttributeError` exception.
221
222 Therefore, the appropriate way to read form data values was to always use the
223 code which checks whether the obtained value is a single value or a list of
224 values. That's annoying and leads to less readable scripts.
225
226 A more convenient approach is to use the methods :meth:`getfirst` and
227 :meth:`getlist` provided by this higher level interface.
228
229
230 .. method:: FieldStorage.getfirst(name, default=None)
231
232 This method always returns only one value associated with form field *name*.
233 The method returns only the first value in case that more values were posted
234 under such name. Please note that the order in which the values are received
235 may vary from browser to browser and should not be counted on. [#]_ If no su ch
236 form field or value exists then the method returns the value specified by the
237 optional parameter *default*. This parameter defaults to ``None`` if not
238 specified.
239
240
241 .. method:: FieldStorage.getlist(name)
242
243 This method always returns a list of values associated with form field *name* .
244 The method returns an empty list if no such form field or value exists for
245 *name*. It returns a list consisting of one item if only one such value exis ts.
246
247 Using these methods you can write nice compact code::
248
249 import cgi
250 form = cgi.FieldStorage()
251 user = form.getfirst("user", "").upper() # This way it's safe.
252 for item in form.getlist("item"):
253 do_something(item)
254
255 240
berkerpeksag 2014/03/19 07:45:59 It would be great to add a complete working exampl
256 .. _functions-in-cgi-module: 241 .. _functions-in-cgi-module:
257 242
258 Functions 243 Functions
259 --------- 244 ---------
260 245
261 These are useful if you want more control, or if you want to employ some of the 246 These are useful if you want more control, or if you want to employ some of the
262 algorithms implemented in this module in other circumstances. 247 algorithms implemented in this module in other circumstances.
263 248
264 249
265 .. function:: parse(fp=None, environ=os.environ, keep_blank_values=False, strict _parsing=False) 250 .. function:: parse(fp=None, environ=os.environ, keep_blank_values=False, strict _parsing=False)
(...skipping 247 matching lines...) Expand 10 before | Expand all | Expand 10 after
513 * Don't try to give a CGI script a set-uid mode. This doesn't work on most 498 * Don't try to give a CGI script a set-uid mode. This doesn't work on most
514 systems, and is a security liability as well. 499 systems, and is a security liability as well.
515 500
516 .. rubric:: Footnotes 501 .. rubric:: Footnotes
517 502
518 .. [#] Note that some recent versions of the HTML specification do state what 503 .. [#] Note that some recent versions of the HTML specification do state what
519 order the field values should be supplied in, but knowing whether a request 504 order the field values should be supplied in, but knowing whether a request
520 was received from a conforming browser, or even from a browser at all, is 505 was received from a conforming browser, or even from a browser at all, is
521 tedious and error-prone. 506 tedious and error-prone.
522 507
OLDNEW
« no previous file with comments | « no previous file | Doc/make.bat » ('j') | Doc/make.bat » ('J')

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+