Text of docs.python.org › 3.11 › library › cgi.html as Styx crawled it on Oct 12, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

cgi — Common Gateway Interface support — Python 3.11.17 documentation

Navigation index modules | next | previous | Python » 3.11.17 Documentation » The Python Standard Library » Superseded Modules » cgi — Common Gateway Interface support | Theme | cgi — Common Gateway Interface support ¶ Source code: Lib/cgi.py Deprecated since version 3.11, will be removed in version 3.13: The cgi module is deprecated (see PEP 594 for details and alternatives). The FieldStorage class can typically be replaced with urllib.parse.parse_qsl() for GET and HEAD requests, and the email.message module or multipart for POST and PUT .

Most utility functions have replacements. Support module for Common Gateway Interface (CGI) scripts. This module defines a number of utilities for use by CGI scripts written in Python. The global variable maxlen can be set to an integer indicating the maximum size of a POST request. POST requests larger than this size will result in a ValueError being raised during parsing. The default value of this variable is 0 , meaning the request size is unlimited.

Availability : not Emscripten, not WASI. This module does not work or is not available on WebAssembly platforms wasm32-emscripten and wasm32-wasi . See WebAssembly platforms for more information. Introduction ¶ A CGI script is invoked by an HTTP server, usually to process user input submitted through an HTML <FORM> or <ISINDEX> element. Most often, CGI scripts live in the server’s special cgi-bin directory. The HTTP server places all sorts of information about the request (such as the client’s hostname, the requested URL, the query string, and lots of other goodies) in the script’s shell environment, executes the script, and sends the script’s output back to the client.

The script’s input is connected to the client too, and sometimes the form data is read this way; at other times the form data is passed via the “query string” part of the URL. This module is intended to take care of the different cases and provide a simpler interface to the Python script. It also provides a number of utilities that help in debugging scripts, and the latest addition is support for file uploads from a form (if your browser supports it).

The output of a CGI script should consist of two sections, separated by a blank line. The first section contains a number of headers, telling the client what kind of data is following. Python code to generate a minimal header section looks like this: print ( "Content-Type: text/html" ) # HTML is following print () # blank line, end of headers The second section is usually HTML, which allows the client software to display nicely formatted text with header, in-line images, etc.

Here’s Python code that prints a simple piece of HTML: print ( "<TITLE>CGI script output</TITLE>" ) print ( "<H1>This is my first CGI script</H1>" ) print ( "Hello, world!" ) Using the cgi module ¶ Begin by writing import cgi . When you write a new script, consider adding these lines: import cgitb cgitb . enable () This activates a special exception handler that will display detailed reports in the web browser if any errors occur.

If you’d rather not show the guts of your program to users of your script, you can have the reports saved to files instead, with code like this: import cgitb cgitb . enable ( display = 0 , logdir = "/path/to/logdir" ) It’s very helpful to use this feature during script development. The reports produced by cgitb provide information that can save you a lot of time in tracking down bugs. You can always remove the cgitb line later when you have tested your script and are confident that it works correctly.

To get at submitted form data, use the FieldStorage class. If the form contains non-ASCII characters, use the encoding keyword parameter set to the value of the encoding defined for the document. It is usually contained in the META tag in the HEAD section of the HTML document or by the Content-Type header. This reads the form contents from the standard input or the environment (depending on the value of various environment variables set according to the CGI standard).

Since it may consume standard input, it should be instantiated only once. The FieldStorage instance can be indexed like a Python dictionary. It allows membership testing with the in operator, and also supports the standard dictionary method keys() and the built-in function len() . Form fields containing empty strings are ignored and do not appear in the dictionary; to keep such values, provide a true value for the optional keep_blank_values keyword parameter when creating the FieldStorage instance.

For instance, the following code (which assumes that the Content-Type header and blank line have already been printed) checks that the fields name and addr are both set to a non-empty string: form = cgi . FieldStorage () if "name" not in form or "addr" not in form : print ( "<H1>Error</H1>" ) print ( "Please fill in the name and addr fields." ) return print ( "<p>name:" , form [ "name" ] . value ) print ( "<p>addr:" , form [ "addr" ] . value ) ... further form processing here ...

Here the fields, accessed through form[key] , are themselves instances of FieldStorage (or MiniFieldStorage , depending on the form encoding). The value attribute of the instance yields the string value of the field. The getvalue() method returns this string value directly; it also accepts an optional second argument as a default to return if the requested key is not present. If the submitted form data contains more than one field with the same name, the object retrieved by form[key] is not a FieldStorage or MiniFieldStorage instance but a list of such instances.

Similarly, in this situation, form.getvalue(key) would return a list of strings. If you expect this possibility (when your HTML form contains multiple fields with the same name), use the getlist() method, which always returns a list of values (so that you do not need to special-case the single item case). For example, this code concatenates any number of username fields, separated by commas: value = form . getlist ( "username" ) usernames = "," . join ( value ) If a field represents an uploaded file, accessing the value via the value attribute or the getvalue() method reads the entire file in memory as bytes.

This may not be what you want. You can test for an uploaded file by testing either the filename attribute or the file attribute. You can then read the data from the file attribute before it is automatically closed as part of the garbage collection of the FieldStorage instance (the read() and readline() methods will return bytes): fileitem = form [ "userfile" ] if fileitem . file : # It's an uploaded file; count lines linecount = 0 while True : line = fileitem . file . readline () if not line : break linecount = linecount + 1 FieldStorage objects also support being used in a with statement, which will automatically close them when done.

If an error is encountered when obtaining the contents of an uploaded file (for example, when the user interrupts the form submission by clicking on a Back or Cancel button) the done attribute of the object for the field will be set to the value -1. The file upload draft standard entertains the possibility of uploading multiple files from one field (using a recursive multipart/* encoding). When this occurs, the item will be a dictionary-like FieldStorage item.

This can be determined by testing its type attribute, which should be multipart/form-data (or perhaps another MIME type matching multipart/* ). In this case, it can be iterated over recursively just like the top-level form object. When a form is submitted in the “old” format (as the query string or as a single data part of type application/x-www-form-urlencoded ), the items will actually be instances of the class MiniFieldStorage .

In this case, the list , file , and filename attributes are always None . A form submitted via POST that also has a query string will contain both FieldStorage and MiniFieldStorage items. Changed in version 3

The rest of this page is on the live site.